Reputation: 7190
Is there a way in AngularJS to programmatically bind a controller method using only javascript(instead of using ng-*
markup)?
Something like
$("#foo").click(FooController.foo)
PS: I don't have access to $compile
Upvotes: 1
Views: 979
Reputation: 5631
You can, but you shouldn't. You'll likely run into trouble down the road.
If you can give a bit more explanation as to why you want to do this, there might be a better (and easier) method.
Upvotes: 1
Reputation: 364677
To extend @Valentyn's answer somewhat, if you had wanted to access a controller method (and not a $scope method) -- e.g., a method defined with this
in the controller constructor function (on the Angular homepage, the "tabs" directive defines function "addPane" on the controller using this
) -- you can use
angular.element('#myid').controller().method()
Upvotes: 1
Reputation: 19391
Do you really need controller's methods or scope's?
in case if you need scope's you can use angular.element('#myid').scope().method
But please keep in mind that any modification of scope's values are not detected if you do them outside of AngularJS event processing, so you need to wrap your code into $apply function of scope.
Also keep in mind that in AngularJS DOM modifications from JS are generally "big no no"
Ofcourse there are controller's functions (created using "this.xxx = function () .."). I am not sure that it is good to access them as they are kind of private, but you should be able to access same way: element(..).controller().method
Upvotes: 3
Reputation: 117370
It is not officially supported. For sure it is technically possible with some hacks but binding event handlers from JavaScript would mean getting access to a DOM element from a controller and it goes against principles of AngularJS.
Upvotes: 2