0

我有一个指令可以监视传入的属性,但是对于该属性,可以传递原始字符串值或表达式。如果传递了一个表达式,那么我需要观察它。但是如果传递了一个原始字符串,那么我真的不需要看这个属性。我想知道是否有一种标准方法可以根据是否传递表达式与字符串来选择性地监视属性?我可以在 attrs 中检查“{{*}}”,但不确定是否完整。

该指令只是这样做:

//my-drct.js
 scope.watch( function(){attrs.specialProperty;} , function(value){ 
   controller.update(value); 
 })

并且 my-drct 可以这样使用:

<div my-drct = '{{foo}}'> //need to watch
//or
<div my-drct = 'foo' >  //dont need to watch
4

1 回答 1

2

You can use the $parse service for that.
The parsed expression has a constant property (boolean), which indicates if the expression is made up by constant parts (so it will stay the same forever) or if it has some dynamic parts as well.

E.g.:

.directive('myDrct', function ($parse) {
    return {
        ...
        link: function myDrctPostLink(scope, elem, attrs) {
            var isConstant = $parse(attrs.myDrct).constant;

            if (isConstant) {
                ...
            } else {
                ...
            }
        }
    };
});

See, also, this short demo.

于 2014-06-29T05:53:59.783 回答