我有一个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中的演示。感谢。
答案 0 :(得分:0)
将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"
};
})
&#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;
使用ng-repeat
时,将ng-model
绑定到基元(ng-model="option"
)会产生&#34; What are the nuances of scope prototypal / prototypical inheritance in AngularJS?&#34;
通过将ng-model
绑定到对象的属性,即config[key]
来避免这种情况。