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



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

该 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 中的演示

。 谢谢。

在指令内移动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"(会产生数据隐藏问题,如"AngularJS中作用域原型/原型继承的细微差别是什么?

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

最新更新