How to pass parameters to an AngularJS controller on creation? I answered this to Yes you absolutely can do so using ng-init
and a simple init function.
Here is the example:
HTML
1 2 3 4 5 6 7 8 9 10 | <!DOCTYPE html> <html ng-app="angularjs-starter"> <head lang="en"> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script> <script src="app.js"></script> </head> <body ng-controller="MainCtrl" ng-init="init('James Bond','007')"> <h1>I am {{name}} {{id}}</h1> </body> </html> |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var app = angular.module('angularjs-starter', []); app.controller('MainCtrl', function($scope) { $scope.init = function(name, id) { //This function is sort of private constructor for controller $scope.id = id; $scope.name = name; //Based on passed argument you can make a call to resource //and initialize more objects //$resource.getMeBond(007) }; }); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.