javascript – scope.$watch在angular指令中不起作用
作者:互联网
我已经制作了一个自定义指令并使用了ng-model,但是当模型更新时,该指令即使我正在观看该事件.这是代码:
angular.module('Directives').directive("customDirective", ['$window', function ($window) {
return {
restrict: "E",
require: 'ngModel',
scope: {
ngModel: '=',
},
link: function (scope, elem, attrs, ngModel) {
// IF the model changes, re-render
scope.$watch('ngModel', function (newVal, oldVal) {
render();
});
// We want to re-render in case of resize
angular.element($window).bind('resize', function () {
//this does work
render();
})
var render = function () {
//doing some work here
};
}
}}]);
和观点:
<div ng-repeat="product in pageCtrl.productList track by product.id">
<h3>{{ product.name }}</h3>
<custom-directive ng-model="product.recentPriceHistory">
</custom-directive>
每当将新值添加到产品recentPriceHistory时,视图都不会更新.
解决方法:
默认情况下,将旧值与新值进行比较时,将检查“参考”相等性.但如果你需要检查价值,那么你需要这样做,
scope.$watch('ngModel', function (newVal, oldVal) {
render();
}, true);
但是这里的问题是angular会深入监视ngModel的所有属性以进行更改.如果ngModel变量是一个复杂的对象,它将影响性能.你可以做到这一点来避免这种情况只检查一个属性,
scope.$watch('ngModel.someProperty', function (newVal, oldVal) {
render();
}, true);
标签:angular-directive,javascript,angularjs,angularjs-ng-repeat,watch 来源: https://codeday.me/bug/20190727/1558338.html