0

How can i pas values to a function with ng-init in a angular project? i have tried this and it works fine:

<div ng-controller="myCtrl" ng-init="myfunction(1)">

but the problem is, when i do this

<div ng-controller="myCtrl" ng-init="myfunction({{id}})">

or

<div ng-controller="myCtrl" ng-init="myfunction(id)">

it doesn't work!! if i show the value of {{id}} in my template i get the id: 1 so the id does exist.

what is here the problem?

Tupic
  • 545
  • 1
  • 6
  • 12
  • 1
    See http://stackoverflow.com/questions/19981627/setting-scope-property-with-ng-init-doesnt-work. Besides that, you are basically trying to call an init function on the controller, passing in a value from the controller? Just access it directly from the init method. – Brendan Green Jan 22 '16 at 01:06
  • First off, `{{id}}` is not meant to be passed as a parameter to the function. The function call is not going to interpolate that. Where is `id` initialized? – frishi Jan 22 '16 at 01:06
  • myFunction needs to be within scope. – user2404597 Jan 22 '16 at 01:17
  • Can you show the code for your controller? – Brendan Green Jan 22 '16 at 01:18

3 Answers3

1

As Brendan Green mentioned, if id is a scope variable you don't need to pass it to the function. Would something like this work?

$scope.myfunction = function(){
  // do whatever with $scope.id
}

If you really need to use it as you are your third example should work. Here is a plunker.

Brendan Green
  • 11,676
  • 5
  • 44
  • 76
Brian Baker
  • 986
  • 1
  • 6
  • 17
0

Created a fiddle here: http://jsfiddle.net/frishi/HB7LU/22553/

Basically, pass in the variable itself to the function and not the interpolated value, i.e. {{boo}}

<div ng-controller="MyCtrl" ng-init="boo=2">
  <div ng-click="foo(boo)">Click Me</div>
</div>
frishi
  • 862
  • 1
  • 10
  • 27
  • What's the point of declaring the variable and then passing it in to an `ng-click`? You might as well just do `ng-click="foo(2)"`, which the OP already stated works in his `ng-init`. The question is about passing a variable into `ng-init`. – Brendan Green Jan 22 '16 at 01:17
  • @BrendanGreen Thanks for correcting me! You are right. – frishi Jan 22 '16 at 12:03
0

In order to use myfunction in ng-init, the function should be defined in your $scopebecause ng-init evaluate expressions whatever they may be.

So here is what you should do:

HTML:

<body ng-controller="MainCtrl" ng-init='myfunction("john");'>
    <p>Hello {{name}}!</p>
  </body>

JS:

app.controller('MainCtrl', function($scope) {
  $scope.name = 'Mike';
  
  $scope.myfunction = function(otherName){
    $scope.name = otherName;
  };
});

Example

Keep in mind that it is not recommended to use ng-init this way:

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.

Community
  • 1
  • 1
user2517028
  • 784
  • 1
  • 11
  • 25