在 this ng-book JSBin ,由于原型(prototype)继承,$scope.$watch()
是否解析为 $rootScope.$watch()
。
我们可以在 Controller 内显式注入(inject) $rootScope
,以便 $scope
与 Controller 内的 $rootScope
相同,而不需要经过原型(prototype)继承?
在此处复制代码以供引用:
// 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
相同的方式注入(inject)它,$rootScope 上定义的任何内容都可以在 Controller 内访问。
app.controller('MyController', ['$scope', '$parse', '$rootScope',
function($scope, $parse, $rootScope) {
$rootScope.foo();
console.log($rootScope.bar);
}
]);
等等
关于javascript - 访问 Controller 中的 $rootScope 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24736872/