gpt4 book ai didi

javascript - 在 Controller 中访问 $rootScope 方法

转载 作者:行者123 更新时间:2023-11-29 19:37:24 25 4
gpt4 key购买 nike

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)它,然后就可以在您的 Controller 中访问在 $rootScope 上定义的任何内容。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com