zoukankan      html  css  js  c++  java
  • Angular 1.x下 select 的一个巨大的坑

    双向绑定这个特性有时让人又爱又恨

    假设控制器

    function($scope){

    $scope.options = [{name:”alex”,id:232,…},{…},{…}…];

    $scope.myModel = {name:”alex”,id:232};

    }

    <select ng-model=”myModel.id”>

    <option value=””>—请选择—</option>

    <option ng-repeat=”opt in options” value=”{{opt.id}}” >

    {{opt.name}}

    </option>

    </select>

    ok,这段看起来很寻常的代码会出现问题

    inspect一下

    fenmgo2f9n3daro0b6

    ?number:45?

    多次调试发现不是程序写得有问题

    这个是angular中select的一个缺陷

    以下是官方说法

    To bind the model to a non-string value, you can use one of the following strategies:

    • the ngOptions directive (select)
    • the ngValue directive, which allows arbitrary expressions to be option values (Example)
    • model $parsers / $formatters to convert the string value (Example)

    然而我尝试了ngOptions时依然无效

    最终解决方案:

    app.directive(‘convertToNumber’, function () {
    return {
    require: ‘ngModel’,
    link: function (scope, element, attrs, ngModel) {
    ngModel.$parsers.push(function (val) {
    return val != null ? parseInt(val, 10) : null;
    });
    ngModel.$formatters.push(function (val) {
    return val != null ? ” + val : null;
    });
    }
    };
    });

  • 相关阅读:
    2008年总结
    感触
    24105
    事情总喜欢蜂拥而至
    最后的稻草
    什么叫服务
    sigh,终于submit了
    在工作和生活的狭缝中生存着
    不应该,不应该
    ren 人 认 忍 韧 仁
  • 原文地址:https://www.cnblogs.com/AlexNull/p/5992344.html
Copyright © 2011-2022 走看看