我非常高兴编码我的指令,但我需要一个属性的观察者,如果前一个值为“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'>⌛</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
请注意,在工作示例中,您可能会发现已经工作的代码略有不同(我使用焦点函数来存储第一次交互后的属性)。我只想知道是否可以以某种方式访问$观察中的属性的前一个值。
'var original = attrs.attributeName'? – charlietfl
那么,这看起来很像“存储它的检查”,此外,我在链接函数中试过,并没有正确存储它(得到未定义),所以我不得不将它存储在改变属性。 – sergio0983
提供[mcve] demo – charlietfl