Javascript 访问控制器中的$rootScope方法
在中,由于原型继承,Javascript 访问控制器中的$rootScope方法,javascript,angularjs,rootscope,Javascript,Angularjs,Rootscope,在中,由于原型继承,$scope.$watch()解析为$rootScope.$watch() 我们是否可以显式地在控制器内部注入$rootScope,以便$scope与控制器内部的$rootScope相同,而不必经过原型继承 在此处复制代码以供参考: // open this example and type person.name into the test field angular.module('myApp', []) .controller('MyContro
$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);
}
});
}]);
如果您打算如此糟糕地使用
rootScope
,那么它与scope
一样有一个提供程序。将'$rootScope'
包含到控制器中,就像使用一样,$scope'
可以实现这一目的
$scope
的$parent
属性也很有用,但在我看来,如果代码被滥用,它往往会降低代码的可维护性。特别是当多个作用域嵌套时,因为您需要遍历整个层次结构。只需以与$scope
或$parse
相同的方式插入它,就可以在控制器内访问在$rootScope上定义的任何内容
app.controller('MyController', ['$scope', '$parse', '$rootScope',
function($scope, $parse, $rootScope) {
$rootScope.foo();
console.log($rootScope.bar);
}
]);
等等。确保它可以被注入,它将不会与$scope相同,
$scope
仍然是root的子级