最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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..

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..

Share Improve this question asked Feb 11, 2015 at 6:47 Udaya RaviUdaya Ravi 1973 gold badges3 silver badges14 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 6

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();
}

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

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.

发布评论

评论列表(0)

  1. 暂无评论