angularjs - 了解 AngularJS 中的 $watch 吗?

标签 angularjs angularjs-directive watch angularjs-scope angularjs-service

我对 AngularJS 中的 $watch 语法有点困惑。

给定一个变量$scope.foo,初始值为[1,2,3],更新后它现在等于[1, 2]。我希望在 $scope.foo 更新时运行一个函数,其中 $scope.foo 作为参数。

如何在 AngularJS 中做到这一点?

最佳答案

这很简单:

function myFunction(foo) {
    // do something with `foo`
}

$scope.$watch('foo', function(newValue, oldValue) { 
    myFunction(newValue);
});

更多详情见 AngularJS documentation about $watch .

关于angularjs - 了解 AngularJS 中的 $watch 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16882406/

相关文章:

angularjs - Angular 指令的内容不会呈现,除非您手动强制页面回流

javascript - Angular 中基于数组值的带有 Promise 的多个 Ajax 请求

angularjs - Angular bindToController 不起作用,可以将对象从一个 Controller 范围绑定(bind)到另一个

AngularJS UI Modal 和 select 不会更新范围值

angularjs - 指令点击被调用两次

linux - 除非命令成功,否则不要更新监视输出

javascript - 如何让 Angular 2 CLI ng 通过子目录提供服务

javascript - AngularJS 指令调用另一个指令未正确传递数据以使用 $compile 进行渲染

javascript - 将数组传递给 $watchGroup 并在更改时更新数组

samsung-mobile - 错误 : Failed to connect to remote target after update to 4. 0.0.2