javascript - angularjs如何为函数设置观察者?

标签 javascript angularjs angularjs-directive

我知道当我有 <p>{{abc}}<p>{{ng-repeat="item in list"}} angularjs 将为 $scope.abc 设置 watcher$scope.list , 因此它们的值将在每个摘要循环中被检查。

但是,当我将 ng-class 指令与一个函数一起使用时,我无法弄清楚 Angular 观察的表达式是什么

angular.module("app",[]).controller("control",function($scope){
  var clicked = false;   
  // this is the variable I would watch for and returnString is the call back...
  // but how could angular possibly know??
  $scope.toggle = function(){
    clicked = !clicked;
  }
  $scope.returnString = function(){
    if(clicked){
      return 'text-success';
    }
    return 'text-danger';
  }
});
<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
    <script data-require="angular.js@1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
  </head>

  <body ng-controller="control">
    <button ng-click="toggle()">click</button>
    <h1 ng-class="returnString()">hello world</h1>
    <!--ng-class="clicked?'text-success':'text-danger'" this way angular knows what to watch...but what if I give it a function???-->
  </body>

</html>

在 html 中...angular 不知道“returnString()”依赖什么值,框架如何设置观察者?还是 Angular 只是在每个摘要循环后运行 ng-class 表达式

最佳答案

AngularJs 也可以在函数上使用 $watch

例如,代替 $watch('abc', function() {/* code */});

你可以这样做

$watch(function() { return $scope.$abc; }, function() { /* code */ });

所以 ng-class 以同样的方式工作:如果你放置一个函数,它将在作用域上下文中应用一个 $watch 到该函数(这意味着该函数需要在当前范围)

参见 $watch AngularDocs 中关于它如何使用函数来观察的文档:

scope.$watch(
  // This function returns the value being watched. It is called for each turn of the $digest loop
  function() { return food; },
  // This is the change listener, called when the value returned from the above function changes
  function(newValue, oldValue) {
    if ( newValue !== oldValue ) {
      // Only increment the counter if the value changed
      scope.foodCounter = scope.foodCounter + 1;
    }
  }
);

被观察的东西是函数的结果,它在每个摘要循环中执行(您可以设置调试断点来验证它)

关于javascript - angularjs如何为函数设置观察者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36164117/

相关文章:

javascript - 一次只允许一种过渡效果

javascript - ngIf 内的绑定(bind)元素不会更新绑定(bind)

javascript - Angular JS 在 div 中发布 ajax 后显示用户错误消息

javascript - 在 redux 中的许多小型可重用 reactjs 组件上使用 connect() 是个好主意吗

javascript - 将动态创建的文本区域中的文本存储在 localStorage 中

javascript - 数据不与 Knockout 绑定(bind)

javascript - ng-click 的奇怪错误

javascript - $resource 函数包装器 angularjs

javascript - 超时时显示一条消息,仅两秒钟

javascript - 无法从自定义指令呈现 templateUrl