How to call multi function in single ng-init directive using angularjs

I'm just trying to call two functions in a single ng-init with angular. But this is a mistake for me. My code is:

ng-init="function1();function2();" 

I do not know how to call this function correctly. Someone can give me some ideas for this. Thanls is moving forward.

+5
source share
3 answers

You can create one main function of type "init" and call other functions inside this function.

 ng-init="init()" 

from your controller

 function init() { function1(); function2(); } 
+5
source

Check out the link below and look at the console.

http://plnkr.co/edit/60Ry6hwiunAF12PZclNW?p=preview

HTML

 <div ng-init='one(); two();'></div> 

Js

 $scope.one = function(){ console.log('one') }; $scope.two = function(){ console.log('two') }; 

Hope this is what you expect

+2
source

First of all, this should work, and probably the reason is that it is not, because you do not have these functions in the field. Do you have ng-controller in this element or ancestor?

If you do this, make sure that these functions are defined in the scope:

 .controller("MainCtrl", function($scope){ $scope.function1 = function(){...}; $scope.function2 = function(){...}; }); 

Secondly, you should not use ng-init to call functions at all.

 <div ng-controller="MainCtrl"> </div> 

Instead, call these functions in the controller:

 .controller("MainCtrl", function($scope){ function1(); function2(); function function1(){...}; function function2(){...}; }); 

From the Angular documentation on ngInit :

The only suitable use of ngInit is to smooth out the special properties of ngRepeat, as shown in the demo below. Other than this case, you should use controllers instead of ngInit to initialize values ​​in the scope.

+1
source

Source: https://habr.com/ru/post/1213112/


All Articles