这整天让我感到困惑。
为什么在文本字段中输入名称时不会更新?一切都是由书决定的。可能出什么问题了?
总结一下:我正在尝试构建一个递归指令,当它遇到一个对象时,它将再次调用自身,直到下降到字符串级别为止。完成后,它会提供一个可以更改字符串的输入(也就是对象中键/值的值)
Here's a JSFiddle
<body ng-app="test">
<div ng-controller="ctrl">
<my-dir the-model="greet"></my-dir>{{greet}}</div>
</body>
angular.module('test', [])
.controller('ctrl', function ($scope) {
$scope.greet = {
"name": "Joe",
"surname": "Norris"
};
})
.directive('myDir', function ($compile) {
var theTemplate =
'<div ng-if="isObject(theModel)">' +
'<div ng-repeat="(k,v) in theModel">'+
'<my-dir the-model="theModel[key]"></my-dir>'+
'</div>'+
'</div>'+
'<div ng-if="!isObject(theModel)">' +
'<input type="text" ng-model="theModel">'+
'</div>'
return {
restrict: 'E',
scope: {
theModel: '='
},
controller: function ($scope) {
$scope.isObject = function (val) {
if (typeof val === 'object') {
console.log("isObject");
return true;
} else{
console.log("is not Object");
return false;
}
}
},
link: function (scope, element) {
element.html(theTemplate); //.append(theTemplate);
$compile(element.contents())(scope);
}
}
});
最佳答案
当我们为ng-model
提供variable name
时,ng-model
将在其编译范围内更新变量。ng-repeat
为每次迭代创建一个新的作用域。
当我们在ng-model
中使用ng-repeat
时,每个ng-model
都将使用ng-repeat创建的新作用域进行编译。因此,这些值不会在控制器的范围内更新。
要更新控制器范围内的值,请使用点表示法。 (即在控制器中创建一个对象并将ng-model绑定到其属性)
关于angularjs - 为什么不使用此递归Angular指令更新模型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28812137/