Reputation: 8137
Every answer I have found involves using an element and accessing $scope
from there.
I want to access scope for a given controller, preferably by controller name, in javascript outside the controller definition. Is this even possible?
For clarity, I'm trying to update a variable being watched on $scope
within the controller. 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);
}
Upvotes: 0
Views: 95
Reputation: 95644
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.
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.
Upvotes: 3