I'm trying to make a directive that inserts elements after an input (which is tagged with the directive) but also updates the input from the inserted elements.
我正在尝试制作一个指令,在输入后插入元素(用指令标记),但也更新插入元素的输入。
angular.module('afterDir', [])
.directive('after', function ($compile) {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
scope.clickHandler = function (index) {
console.log(index);
ngModel.$setViewValue("something");
}
var content = angular.element('<ul><li ng-click="clickHandler()">after</li><li ng-click="clickHandler()">after too</li></ul>');
content.insertAfter(element);
$compile(content)(scope);
}
}
});
The click handler fires but the model does not update, is there something else I need to call to update the model? Thanks!
点击处理程序触发但模型没有更新,是否还需要调用其他内容来更新模型?谢谢!
1 个解决方案
#1
2
If you add an ngModel.$render() after your $setViewValue() you should get what you need.
如果你在$ setViewValue()之后添加一个ngModel。$ render(),你应该得到你需要的东西。
Here's a plunkr. http://plnkr.co/edit/nZgMiZZD4Vna6vMb4LZr
这是一个傻瓜。 http://plnkr.co/edit/nZgMiZZD4Vna6vMb4LZr
For some explanation, $setViewValue will update the controllers internal viewValue, it will dirty the form if needed, and it will update the internal modelValue as well as the model itself.
对于一些解释,$ setViewValue将更新控制器内部viewValue,如果需要它将脏化表单,它将更新内部modelValue以及模型本身。
$render will actually take that internal viewValue and push it to the DOM.
$ render实际上将获取内部viewValue并将其推送到DOM。
#1
2
If you add an ngModel.$render() after your $setViewValue() you should get what you need.
如果你在$ setViewValue()之后添加一个ngModel。$ render(),你应该得到你需要的东西。
Here's a plunkr. http://plnkr.co/edit/nZgMiZZD4Vna6vMb4LZr
这是一个傻瓜。 http://plnkr.co/edit/nZgMiZZD4Vna6vMb4LZr
For some explanation, $setViewValue will update the controllers internal viewValue, it will dirty the form if needed, and it will update the internal modelValue as well as the model itself.
对于一些解释,$ setViewValue将更新控制器内部viewValue,如果需要它将脏化表单,它将更新内部modelValue以及模型本身。
$render will actually take that internal viewValue and push it to the DOM.
$ render实际上将获取内部viewValue并将其推送到DOM。