我制作了一个指令,旨在使用ngModel指令附加到元素.如果模型的值匹配,则应将值设置为先前的值.在我的例子中,我正在寻找"foo",并将其设置回前一个,如果这是输入的内容.
我的单元测试在这方面很好,因为他们只关注模型值.但是在实践中,当"回放"触发时,DOM不会更新.我们在这里最好的猜测是设置old == new可以防止脏检查发生.我逐步完成了$ setViewValue方法,它看起来正在做它应该做的事情.但是,在我设置新值之后显式调用ngModel.$ render()之前,它不会更新DOM(以及您在浏览器中看到的内容).它工作正常,但我只想看看是否有更合适的方法.
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
terminal: true,
require: "?ngModel",
link: function (scope, element, attrs, ngModel) {
scope.$watch(attrs.ngModel, function (newValue, oldValue) {
//ngModel.$setViewValue(newValue + "!");
if (newValue == "foo")
{
ngModel.$setViewValue(oldValue);
/*
I Need this render call in order to update the input box; is that OK?
My best guess is that setting new = old prevents a dirty check which would trigger $render()
*/ …
Run Code Online (Sandbox Code Playgroud)