我的内容中有一个代码段,它是从http获取的模型。我正在使用语法高亮显示来美化代码。所以我需要在针对特定模型更新DOM时立即调用javascript函数。
这是一个清晰的示例代码。我正在使用警报来演示它。在我的项目中,我将使用第三方插件,它将找到匹配的dom元素并重新构建它们。 这里, 我希望在显示列表后发生警报
jsfiddle: http://jsfiddle.net/7xZde/2/
我的控制器有这样的东西。
$scope.items = Model.notes();
alert('test');
警报甚至在显示项目列表之前出现,我希望在列表显示之后。
任何暗示可以帮助我实现这一目标。
答案 0 :(得分:1)
我们需要使用$ timeout,
$scope.items = Model.notes();
$timeout(function () {
alert('test');
})
是的,这很愚蠢,$ timeout似乎对我来说是个用词不当。我是2天大的angularjs。抱歉浪费你的时间。
答案 1 :(得分:0)
幸运的是,我想做同样的事情。变异观察者是前进的道路,但如果您需要向后兼容旧版浏览器,则需要更多代码。
适用于Firefox,Chrome和Safari的使用Javascript:
var app = angular.module('plunker', [])
.controller('MainCtrl', function($scope) {
$scope.name = 'World';
})
.directive('watchChanges', function ($parse, $timeout) {
return function (scope, element, attrs) {
var setter = $parse(attrs.watchChanges).assign;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
$timeout(function () {
var text = angular.element('<div></div>').text(element.html()).text();
setter(scope, text);
});
});
});
// configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true,
subtree: true
};
// pass in the target node, as well as the observer options
observer.observe(element[0], config);
};
});
HTML:
<body ng-controller="MainCtrl">
<div watch-changes="text">
<p>Hello {{ name }}</p>
<label>Name</label>
<input type="text" ng-model="name" />
</div>
<pre>{{text}}</pre>
</body>