Angularjs directive creates watches

倾然丶 夕夏残阳落幕 提交于 2019-12-08 10:37:46

问题


I have an angular directive that creates a numeric spinner (<input type="number>) which one can pass in a minimum and maximum to.

However I have noticed that angular will create a watch for the min and max values passed to the directive, as well as where min and max are used in the template. This is a problem as in reality there will be a number more paramaters that can be passed in, and this is inside of a large ng-repeat.

The directive is as follows:

.directive('inputNumber', function () {
    return {
        restrict: 'E',
        scope:{
            min: '@',
            max: '@'
        },
        template: '<input type="number" min="{{min}}" max="{{max}}" ng-model="value"/>',
        link: function($scope, $element, $attrs) {
            $scope.value = parseFloat($scope.min);
        }
    }
})

And is used as so:

<input-number data-min="{{min}}" data-max="{{max}}"></input-number>

I have no need for the watches as the values will never change once they are set, so I can use one-time bindings within my template:

template: '<input type="number" min="{{::min}}" max="{{::max}}" ng-model="value"/>'

One-time binding can also be used on the directive itself.

However this means all developers will need this taught to them so that they know to use this approach. Therefore is there anyway to avoid the one-time binding when the directive is used, but still get the benefit of it?

JSFiddle without one-time bindings

JSFiddle with one-time bindings

Update

It also seems that if you use a two-way binding then angular creates two watches, one for each end of the binding. Is where any way to get around this either?


回答1:


You could manually get the interpolated values once with $parse or scope.$eval, and use one-time binding ({{::var}}) inside the template:

.directive('inputNumber', function ($parse) {
   scope: {},
   template: '<input type="number" min="{{::min}}" max="{{::max}}" ng-model="value"/>',
   link: function($scope, $element, $attrs){
     $scope.min = $parse($attrs.min)($scope.$parent);
     $scope.max = $parse($attrs.max)($scope.$parent);
     // etc...
   }
}

The usage would be:

<input-number data-min="min" data-max="max"></input-number>


来源:https://stackoverflow.com/questions/30193069/angularjs-directive-creates-watches

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!