I was very happy coding my directive, but I needed an observer on an attribute that had to fire only if the previous value was "x". The problem is, that $observe
doesn´t seem to provide the previous value, as $watch
does.
Is there a fast way to access an attribute previous value, or do I have to store it for checks?
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();
}
});
...
Ignored the rest of the code, as irrelevant for my question. If you want a complete, working example: http://codepen.io/sergio0983/pen/XKEQqg?editors=1010
Note that in the working example you might find slightly different code (I used the focus function to store the attribute after the first interaction) that is already working. I only want to know if I can access the previous value of the attribute in $observe somehow.