angular call a function and pass id

4.5k Views Asked by At

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?

3

There are 3 best solutions below

2
On

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>
0
On

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.

0
On

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.