简体   繁体   English

访问没有元素的角度$ scope

[英]Access angular $scope without element

Every answer I have found involves using an element and accessing $scope from there. 我找到的每个答案都涉及使用一个元素并从那里访问$scope

I want to access scope for a given controller, preferably by controller name, in javascript outside the controller definition. 我想在控制器定义之外的javascript中访问给定控制器的范围,最好按控制器名称访问。 Is this even possible? 这有可能吗?


For clarity, I'm trying to update a variable being watched on $scope within the controller. 为了清楚起见,我试图更新在控制器中的$scope上正在监视的变量。 I want to have one standalone function that I can pass some parameters into that can perform this function for a multitude of controllers in my application. 我希望有一个独立的函数,可以将一些参数传递给该函数,以对我的应用程序中的多个控制器执行此函数。

If I'm going about this completely the wrong way please correct me. 如果我完全以错误的方式进行操作,请纠正我。 Just started getting in to angular recently. 最近才刚开始接触角度。


Something like: 就像是:

var myapp = angular.module("myapp", []);

myapp.controller("myController1", function($scope, $http){
    $scope.specialVar = "some value";
});
myapp.controller("myController2", function($scope, $http){
    $scope.specialVar = "some other value";
});

var myFunction = function(controller, val){
    //set the value of specialVar for the passed controller to the passed value
    myapp.AccessController(controller).$scope('specialVar', val);
}

Remember that you can have any number of instances of a given controller coexisting in your application, but only one service; 请记住,在您的应用程序中可以同时存在给定控制器的任意数量的实例,但只能有一个服务。 services are effectively singleton. 服务是有效的单例。 If you're able to assume that there's only ever exactly one instance of a given controller, then it sounds like you're treating that controller as a service, and that you should just use the service instead. 如果您能够假定给定控制器只有一个实例,那么听起来就像您将该控制器视为服务,而应该只使用该服务。 If you're not able to assume that there's only ever exactly one instance, then you absolutely need to access through angular.element(domElement).scope() , because otherwise you're going to have a hard time selecting which of the many instances you're talking about. 如果您无法假设只有一个实例,那么您绝对需要通过angular.element(domElement).scope()进行访问,因为否则您将很难选择很多实例。您正在谈论的实例。

Remember, you can always use a service and a dictionary/object to map from an arbitrary key into a given scope, if you'd rather not use the element to look up the scope. 请记住,如果您不想使用元素来查找范围,则始终可以使用服务和字典/对象将任意键映射到给定的范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM