AngularJS 整个应用程序中可用的功能

例子

请注意,对于角度应用程序,此方法可能被认为是不好的设计,因为它要求程序员记住函数在作用域树中的放置位置,并要注意作用域继承。在许多情况下,最好注入服务(Angular实践-使用范围继承与注入。

此示例仅显示范围继承如何用于我们的需求,以及如何利用它,而不是设计整个应用程序的最佳实践。

在某些情况下,我们可以利用范围继承,并将函数设置为rootScope的属性。这样-应用程序中的所有范围(隔离范围除外)都将继承此函数,并且可以从应用程序中的任何位置调用它。

angular.module('app', [])
.run(['$rootScope', function($rootScope){
    var messages = []
    $rootScope.addMessage = function(msg){
        messages.push(msg);
    }
}]);

<div ng-app="app">
    <a ng-click="addMessage('hello world!')">it could be accsessed from here</a>
    <div ng-include="inner.html"></div>
</div>

inner.html:

<div>
    <button ng-click="addMessage('page')">and from here to!</button>
</div>