我有一个模板,可以在运行时动态创建输入元素。我想将输入到此输入元素的数据捕获到我的模型中。我正在尝试使用 ng-model 来实现这一目标。但是,它不起作用。在检查元素时,我发现正确的表达式已绑定(bind)到 ng-model,但它没有更新我的模型。这是我的代码:
模板:
<div child-ng-model="userReg.candidateData.PrimarySkills">
<!-- this div creates an input element on runtime -->
</div>
指令:
(function (window) {
'use strict';
angular.module('myApp.userRegistration.directive')
.directive('childNgModel', ['$compile', function ($compile) {
return {
restrict: 'A',
scope: {
childNgModel: '@'
},
link: function (scope, element, attrs) {
var el = element.children().eq(0);
el.attr('ng-model', scope.childNgModel);
$compile(el)(scope);
}
}
}]);
})(window);
我在输入字段中输入的文本没有被我的模型捕获(userReg.candidateData.PrimarySkills)。为什么会发生这种情况?我在这里做错了什么?
最佳答案
问题是您正在指令中创建一个独立的范围。因此,ngModel 无法写入外部作用域变量。
尝试以下操作:
(function (window) {
'use strict';
angular.module('myApp.userRegistration.directive')
.directive('childNgModel', ['$compile', function ($compile) {
return {
restrict: 'A',
scope: true, // create a normal child scope
link: function (scope, element, attrs) {
var el = element.children().eq(0);
el.attr('ng-model', attrs.childNgModel); // just get the attribute value
$compile(el)(scope);
}
}
}]);
})(window);
关于javascript - 在动态创建的元素上使用 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40080024/