Failed to get AngularJS controller object

In my angular code I am getting controller object via following code

var controllerElement = angular.element('[ng-controller="' + controllerName + '"]');
var controller = controllerElement.controller();

      

It worked fine until the day before last when there is $ get.h {} instead of the controller object of the controller object

The following code returns the correct controller object, but there is a scenario where angular throws an exception:

var $controller = injector.get("$controller");
var controller = $controller(controllerName, { $scope: scope });

      

Could you please help me figure out what is the problem with the old approach, i.e. controllerElement.controller ();

EDIT: Found another question with the latest approach that instantiates a new controller object instead of returning the original one associated with the element.

+3


source to share


1 answer


I would highly recommend not mixing angular code with external JS. Every time you call Controller

it creates a really new object, but as far as I understood from your question, you probably want to do some manipulation on it or its data. For persistent data between controllers or states of your application, you must use Service

either Factory

, and manipulation must occur in it, or from Controller

some random JS somewhere.



+1


source







All Articles