我非常高興編碼我的指令,但我需要一個屬性的觀察者,如果前一個值爲「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