Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get AngularJS controller object

In my non-angular code I am getting controller object through following code

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

It was working perfectly until day before yesterday when instead of controller object controller object has some $get.h {}

Following code returns correct controller object but there is a scenario in which angular is throwing exception:

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

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

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

like image 283
Haris Avatar asked Jun 20 '26 04:06

Haris


1 Answers

I would strongly recommend not to mix angular code with external JS. Every time you are calling a Controller, it will created indeed a new object, but as far as I understood from your question, you probably want to do some manipulation in it or its data. For persistent data across controllers or states of your application you should use a Service or a Factory, and manipulating it should happen in it, or from a Controller not some random JS somewhere.

like image 50
topless Avatar answered Jun 22 '26 17:06

topless



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!