【问题标题】:Edit object properties by using a two ways binding directive doesn't work使用绑定指令不起作用的两种方式编辑对象属性
【发布时间】:2018-05-14 06:17:10
【问题描述】:

我有一个 json,我想在 ng-repeat 中显示每个项目的输入以进行编辑。

json:

$scope.setup.configuration = {
    "filename": "configuration", 
    "fileversion": "01.00.0000"
};

指令(在范围内使用“=”进行两种方式绑定):

 app.directive("kSetupOption", ['$rootScope',function ($rootScope) {
        return {
            scope:{
                key:"=",
                option:"="
            },
            restrict: 'E',
            template:'<p>{{key}}: <input ng-model="option" /></p>',
            link: function (scope, element, attrs) {
              }
            }
    }]);

问题在于 2 路绑定可以正常工作:

<input ng-model="setup.configuration.filename">

但不是在这段代码中使用指令:

<k-setup-option
    ng-repeat="(key , option) in setup.configuration" 
    option="option" 
    key="key" ></k-setup-option>

请参阅Plunker 中的演示。谢谢。

【问题讨论】:

  • 笨蛋。链接失效请修改
  • 完成。谢谢
  • @Fabrice 因为ng-repeat 是每次迭代时的指令,它生成的新实例有自己的范围,你提到= 没关系。更新了你的 plunker plnkr.co/edit/HdclYxw1mCAgpQYR38Ia?p=preview

标签: angularjs data-binding


【解决方案1】:

在指令内移动ng-repeat

angular.module('app', [])
.directive("kSetupOption", function () {
    return {
            scope:{
                config:"<",
            },
            restrict: 'E',
            template:`<p ng-repeat="(key,option) in config">
                       {{key}}: <input ng-model="config[key]" />
                      </p>`,
            link: function (scope, element, attrs) {
            }
    };
})
.controller('ctrl', function($scope) {
  var MC = $scope;
  MC.setup = {};
  MC.setup.configuration = {
            "filename": "configuration", 
            "fileversion": "01.00.0000"
  };
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
    
    <k-setup-option config="setup.configuration"></k-setup-option>
  
    <h2>setup.configuration:</h2> 
    <div style="background-color:#f9f0b3">{{setup.configuration}}</div>  
</body>

使用ng-repeat 时,将ng-model 绑定到原语(ng-model="option")会产生“What are the nuances of scope prototypal / prototypical inheritance in AngularJS?”中描述的数据隐藏问题

通过将ng-model 绑定到对象的属性(即config[key])来避免这种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多