使用双向绑定指令编辑对象属性不起作用

时间:2018-05-14 06:17:10

标签: angularjs data-binding

我有一个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) {
              }
            }
    }]);

问题是双向绑定对此有效:

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

但是没有使用该指令的代码:

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

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

1 个答案:

答案 0 :(得分:0)

ng-repeat移到指令内:

&#13;
&#13;
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"
  };
})
&#13;
<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>
&#13;
&#13;
&#13;

使用ng-repeat时,将ng-model绑定到基元(ng-model="option")会产生&#34; What are the nuances of scope prototypal / prototypical inheritance in AngularJS?&#34;

中描述的数据隐藏问题

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