[英]When does AngularJS propagate model changes to the DOM?
在AngularJS中,您可以使用$watch
模型更改。 所以,如果我寫這樣的話:
$scope.$watch('model', function (newValue, oldValue) {
// React to the change...
});
...然后當模型$scope.model
更改並執行某些操作時,我會收到通知。
但是,如果該model
綁定到AngularJS視圖(即, model.name
綁定到HTML頁面上的用戶名),則在$watch
回調觸發時,此更改尚未傳播到DOM。
我的問題是:AngularJS何時將模型更改傳播到DOM,我如何偵聽該事件?
編輯
用例是制作一個絕對定位的滾動器,該滾動器具有可變大小的固定標題和滾動內容(請參閱此Plunk以獲得一個想法: http ://plnkr.co/edit/LdYl7e7GYhdGiF3NQ0Bv)
指令現在看起來像這樣:
.directive('psScroller', function ($timeout) {
return {
require: 'ngModel',
replace: true,
restrict: 'A',
transclude: true,
scope: {
'model': '=ngModel'
},
controller: function ($scope) {
var _this = this;
var _headerElement;
var _contentElement;
$scope.resize = function () {
if (!_headerElement || !_contentElement) return;
$timeout(function() {
_contentElement.css('top', _headerElement.height())
});
};
this.setHeaderElement = function (headerElement) {
_headerElement = headerElement;
_headerElement.on('keydown', $scope.resize);
};
this.setContentElement = function (contentElement) {
_contentElement = contentElement;
};
},
link: function (scope) {
scope.$watch('model', function () {
scope.resize();
}, true);
},
template: '<div ng-transclude></div>'
};
});
因此,我的想法是調整內容高度以匹配標題高度。
Angular指令負責反映DOM中的模型更改。 它們在模型元素上注冊監視程序,並在調用這些監視程序時更改DOM。 因此,當您監視與指令相同的模型屬性時,您的監視偵聽器可能在由相應偽指令注冊的監視偵聽器之前被調用,因此DOM尚未更改。
您可以在監視偵聽器中使用超時或$scope.$evalAsync()
來延遲代碼的執行並等待DOM更改。 例如,在對一個相關問題的答案中 ,說明了兩種解決方案的不同之處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.