[英]Accessing $rootScope methods in Controller
在此ng書JSBin中 ,由於原型繼承, $scope.$watch()
解析為$rootScope.$watch()
。
我們是否可以在控制器內部顯式注入$rootScope
,以便$scope
與控制器內部的$rootScope
相同,而無需進行原型繼承?
在此處復制代碼以供參考:
// open this example and type person.name into the test field
angular.module('myApp', [])
.controller('MyController',
['$scope', '$parse', function($scope, $parse) {
$scope.person = {
name: "Ari Lerner"
};
$scope.$watch('expr', function(newVal, oldVal, scope) {
if (newVal !== oldVal) {
// Let's set up our parseFun with the expression
var parseFun = $parse(newVal);
// Get the value of the parsed expression, set it on the scope for output
scope.parsedExpr = parseFun(scope);
}
});
}]);
只需以與$scope
或$parse
相同的方式注入它,即可在控制器內部訪問$ rootScope上定義的任何內容。
app.controller('MyController', ['$scope', '$parse', '$rootScope',
function($scope, $parse, $rootScope) {
$rootScope.foo();
console.log($rootScope.bar);
}
]);
等等
如果您打算如此嚴重地使用rootScope
,則它與scope
一樣具有提供程序。 像使用'$scope'
一樣,將'$rootScope'
包含到控制器中就可以了。
$scope
的$parent
屬性也可以派上用場,但是IMO傾向於使代碼在被濫用時難以維護。 特別是當嵌套多個作用域時,您需要遍歷整個層次結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.