Udaya Ravi
Udaya Ravi

Reputation: 197

how to call multi function in single ng-init directice using angularjs

I just try to call two function in single ng-init of angularjs.but it through error to me. My code:

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

I don't know how to call those function correctly.anyone can give me some ideas to do it.
Thanls advance..

Upvotes: 7

Views: 44288

Answers (3)

New Dev
New Dev

Reputation: 49590

First of all, this should work, and probably the reason it doesn't is because you don't have these functions in the scope. Do you have an ng-controller on this or ancestor element?

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

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

Second, you should not be using 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 Angular documentation on ngInit:

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

Upvotes: 1

Sandeeproop
Sandeeproop

Reputation: 1776

You can create one main function like "init" and call other functions inside that function.

ng-init="init()"

from your controller

function init() {
  function1();
  function2();
}

Upvotes: 6

Rajeshwar
Rajeshwar

Reputation: 2519

Check out the below link, and have a 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 are expecting

Upvotes: 5

Related Questions