在$ observe函数中检索属性

时间:2016-07-22 13:03:09

标签: angularjs

我很高兴编写我的指令,但我需要一个属性的观察者,只有在前一个值为“x”时才需要触发。问题是,$observe似乎没有像$watch那样提供以前的值。

是否有快速访问属性的前一个值,或者我是否必须将其存储以进行检查?

HTML:

<searcher ng-datasource = 'countries' ng-model = 'chosenCountry' placeholder = 'Search Country' ng-alias = 'country' ng-tuples = 'country as country.name' ng-rows-by-page = 2>

JS

app.directive("searcher", function($datasources, $document){
    return {
        restrict: 'E',
        require: '?ngModel',
        scope: {
            ngModel: '='
        }, 
        replace:true,
        template:
            "<md-select ng-attr-active = '{{hasFocus}}' ng-attr-empty = '{{!searchText}}'>"+
            "   <md-input ng-click = 'handleClick();'>"+
            "       <a class = 'fa fa-search icon' ng-if = '!searchPromise'></a>"+
            "       <a class = 'fa fa-spin icon' ng-if = 'searchPromise'>&#8987;</a>"+
            "       <input type = 'text' ng-model = 'searchText' ng-keydown = 'handleKeydown()' ng-focus='handleFocus()'>"+
            "   </md-input>"+
            "   <ul>"+
            "       <li ng-repeat = 'row in __rows track by $index' ng-click = 'choose(row)'>{{txt(row)}}</li>"+
            "   </ul>"+
            "</md-select>"+
        "",
        link: function( scope, element, attrs, ctrl ) {

....
attrs.$observe("active", function(newValue){
                if ( newValue == "false" ){
                    ctrl.$setTouched();
                }
            });
...

忽略其余的代码,与我的问题无关。如果您想要一个完整的,有效的示例:http://codepen.io/sergio0983/pen/XKEQqg?editors=1010

请注意,在工作示例中,您可能会发现稍有不同的代码(我在第一次交互后使用了焦点函数来存储属性)。我只想知道我是否可以以某种方式访问​​$ observe中的属性的先前值。

1 个答案:

答案 0 :(得分:0)

$scope.$watch('someAttr',function(newValue,oldValue){
   if(oldValue === 'x'){
     // do something
   }
});