隔离范围指令和AngularJS中的$ observer

时间:2015-12-13 00:04:48

标签: javascript angularjs angular-directive

我正在继续我的悲剧之旅,试图学习如何在AngularJS中写出好的指令......但在阅读了很多文章之后我才会遇到同样的问题和问题。 这是我的测试指令:http://plnkr.co/edit/rjR8Q2TQi59TWSW0emmo?p=preview

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)有没有更好的方法来更新值而不使用$ observe? (我在这里读到:https://www.accelebrate.com/blog/effective-strategies-avoiding-watches-angularjs/但是没有一个解释过的方法看起来很干净,它们似乎只是hacky-workarounds)。

3)$ watch和$ observe之间有任何性能差异吗? (哪个更好?我已经到处阅读尽可能少使用$ watch,对于$ observe来说是一样的。)

感谢所有能让我清楚所有这些内容的人!

1 个答案:

答案 0 :(得分:2)

  1. 和2.使用$timeout服务。 setTimeout不会告知Angular它所做的更改。您必须在回调中手动触发$digest周期,$timeout为您处理。
  2. 有关详细信息,请参阅this article

    1. 通常,$watch$observe在性能方面是相同的。它们表明您的代码可以得到改进。根据经验,一旦你在一个页面上找到2000个观察者,它往往会变得迟钝。