我制作了一个应用程序(使用 AngularJS 1.X 构建),它有很多指令,其中大多数都有自己的隔离范围。因此,对于每个新的 $scope
我分配 Underscore.js
+ Underscore.string
变量 _
和 s
给他们,就像这样:
controller: function($scope){
$scope._ = _;
$scope._s = s;
$scope.foo = 'my-example-here';
}
然后在独立的范围模板中做一些像这样很酷的事情:
<div ng-bind='s.humanize(some_id)'></div> # output: "My example here"
不幸的是,您无法访问这些范围内的全局变量。
那么,最终如何为每个 AngularJS $scope
添加一致的变量或函数?
最佳答案
试试这个:
app.controller('MyCtrl', function($rootScope) {
$rootScope.derp = "foo!";
});
app.directive('myDir', function($rootScope) {
return {
scope { ... },
controller: function($rootScope) {
console.log($rootScope.derp);
}
};
});
确保将 ng-controller="MyCtrl"
指令放置在自定义指令的父 DOM 元素上的某个位置,如下所示:
<div ng-controller="MyCtrl">
<div my-dir></div>
</div>
请尝试一下。
编辑 另外,您可以使用constants正如@georgeawg 在评论中所描述的。
关于javascript - 如何向每个 AngularJS $scope 添加一致的变量或函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36031476/