2016-07-22 63 views
0

我非常高兴编码我的指令,但我需要一个属性的观察者,如果前一个值为“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

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

+0

'var original = attrs.attributeName'? – charlietfl

+0

那么,这看起来很像“存储它的检查”,此外,我在链接函数中试过,并没有正确存储它(得到未定义),所以我不得不将它存储在改变属性。 – sergio0983

+0

提供[mcve] demo – charlietfl

回答

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

我是一个角度新手,但如果我没有错,$ scope。$ watch用于范围内的变量,attrs。$观察DOM节点中的属性,这就是我需要的,因此是问题。使用$ scope。如果你放置一个属性,$ watch将总是返回“undefined”。不是100%确定,只是纠正我,如果我错了 – sergio0983

+1

http://stackoverflow.com/a/14907826/3503831 – krutkowski86

+0

确切地说,我的情况,它是一个插值的属性;感谢您的信息。 – sergio0983