0
我继续我的悲剧旅程努力学习如何编写AngularJS好的指令$观察员......但阅读我周围的很多文章后只是有相同的问题和存在的问题。 这里是我的测试指令:http://plnkr.co/edit/rjR8Q2TQi59TWSW0emmo?p=preview隔离范围指令,并在AngularJS
HTML:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="myController">
<span my-directive caption="{{foo}}"></span>
<span my-directive caption="{{bar}}"></span>
</body>
</html>
JS:
app = angular.module('app', []);
app.controller('myController', ['$scope', function ($scope) {
$scope.foo = "initial foo";
setTimeout(function() { // <-- simulate an async call or whatever...
console.log('after 3 sec in foo:');
$scope.foo = "changed foo";
}, 3000);
$scope.bar = "initial bar";
setTimeout(function() { // <-- simulate an async call or whatever...
console.log('after 3 sec in bar:');
$scope.bar = "changed bar";
}, 3000);
}]);
app.directive('myDirective', function() {
return {
restrict: 'A',
scope: {
caption: '@'
},
link: function(scope, element, attrs) {
attrs.$observe('caption', function(value) {
console.log(value);
})
}
}
});
我的问题是:
1)为什么它没有得到更新标题值延迟后?
2)是否有更好的方式来获得,而无需使用$观察更新的值? (我在这里读到:https://www.accelebrate.com/blog/effective-strategies-avoiding-watches-angularjs/但没有解释的方法似乎干净,他们只是似乎hacky变通办法)。
3)是否有$手表和$遵守之间的性能差异? (哪个更好?我已经阅读到处都是使用$ watch,尽可能少,对于$ observe也是一样的)。
谢谢你给任何人,这将让我清楚所有这些东西!
非常感谢你,我还不知道呢! – wizzy