Angularjs指令创建手表 [英] Angularjs directive creates watches

查看:136
本文介绍了Angularjs指令创建手表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建一个数字微调的角度指令(<输入类型=号> )。它可以在最小和最大传递

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

不过,我已经注意到,角将创建传递给指令的手表和最大值,以及其中,最大在模板中使用。这是因为在现实中会出现,可以在传递一些更PARAMATERS一个问题,这是一个大的 NG-重复内

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.

该指令如下:

.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);
        }
    }
})

和用作这样:

<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没有一次性绑定

的jsfiddle 一次性绑定

JSFiddle with one-time bindings

这也似乎是,如果你使用一个双向绑定,然后创建角两只手表,一个用于绑定的两端。在这里没有办法来解决这个问题要么?

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?

推荐答案

您可以手动与 $解析范围得到插值​​一次。 $ EVAL ,并使用一次性绑定( {{VAR ::}} )的模板中:

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...
   }
}

的用法是:

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

这篇关于Angularjs指令创建手表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆