在 AngularJS 中隔离作用域指令和 $observer

Isolate scope directive and $observer in AngularJS

我正在继续我的悲剧之旅,试图学习如何在 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/ 但是 none 的解释方法看起来很干净,它们看起来只是 hacky-workarounds)。

3) $watch 和 $observe 在性能上有什么区别吗? (哪个更好?我到处都读到要尽可能少地使用 $watch,$observe 也是一样)。

感谢任何能让我弄清楚所有这些东西的人!

  1. 和 2. 使用 $timeout 服务。 setTimeout 不会通知 Angular 它所做的更改。您必须在回调中手动触发 $digest 循环,$timeout 会为您处理。

有关详细信息,请参阅 this article

  1. 一般来说,$watch$observe 在性能方面是相同的。它们表明您的代码可以改进。根据经验,一旦页面上有大约 2000 名观察者,它就会变得缓慢。