AngularJS : ng-model 在指令内部时不绑定两种方式
AngularJS : ng-model not binding two ways when inside a directive
我在这里阅读了一些关于这个主题的帖子,但所有答案和所有 fiddles 我都没有看到一个正常工作。我让我的 plunkr 将动态生成的字段通过指令隔离范围内的 ng-model 绑定到父级中的表单的单向绑定。但是,它不会从表单绑定回指令。我的初始值被忽略了,我在父范围内所做的更改也被忽略了,我真的很想要一个解决方案。这是一个代码片段。
<div ng-repeat="field in fields">
<app-field field="field" ng-model="selected[field.name]" form="form"></app-field>
</div>
...
.directive("appField", function($http, $compile) {
return {
restrict: "AE",
scope: {
field: "=",
ngModel: "=",
form: "="
},
link: function($scope, element, attrs) {
$http.get("field.html").then(function (result) {
element.html(result.data);
$compile(element.contents())($scope);
});
}
}
})
这是我的 fiddle:http://plnkr.co/edit/ZzC4jS9M9Ev5i6gxUVxB?p=preview
如有任何帮助,我们将不胜感激。
属性 是 scope
,而不是 $scope
。然后,删除 scope:false
就完成了!
此外,您可以使用 templateUrl
属性 代替 link
(在本例中):
.directive("appField", function($http, $compile) {
return {
restrict: "AE",
scope: {
field: "=",
ngModel: "=",
form: "="
},
templateUrl: 'field.html'
}
})
我在这里阅读了一些关于这个主题的帖子,但所有答案和所有 fiddles 我都没有看到一个正常工作。我让我的 plunkr 将动态生成的字段通过指令隔离范围内的 ng-model 绑定到父级中的表单的单向绑定。但是,它不会从表单绑定回指令。我的初始值被忽略了,我在父范围内所做的更改也被忽略了,我真的很想要一个解决方案。这是一个代码片段。
<div ng-repeat="field in fields">
<app-field field="field" ng-model="selected[field.name]" form="form"></app-field>
</div>
...
.directive("appField", function($http, $compile) {
return {
restrict: "AE",
scope: {
field: "=",
ngModel: "=",
form: "="
},
link: function($scope, element, attrs) {
$http.get("field.html").then(function (result) {
element.html(result.data);
$compile(element.contents())($scope);
});
}
}
})
这是我的 fiddle:http://plnkr.co/edit/ZzC4jS9M9Ev5i6gxUVxB?p=preview
如有任何帮助,我们将不胜感激。
属性 是 scope
,而不是 $scope
。然后,删除 scope:false
就完成了!
此外,您可以使用 templateUrl
属性 代替 link
(在本例中):
.directive("appField", function($http, $compile) {
return {
restrict: "AE",
scope: {
field: "=",
ngModel: "=",
form: "="
},
templateUrl: 'field.html'
}
})