nickponline nickponline - 1 year ago 92
AngularJS Question

Can you pass parameters to an AngularJS controller on creation?

I have a controller responsible for communicating with an API to update properties of a user, name, email, etc. Each user has an

which is passed from the server when the profile page is viewed.

I would like to pass this value to the AngularJS controller so it knows what the API entry point is for the current user. I've tried passing the value in
. For example:

function UserCtrl(id, $scope, $filter) {

$scope.connection = $resource('' + id)

and in the HTML

<body ng-controller="UserCtrl({% id %})">

{% id %}
print the id sent from the server. but I get errors.

What is the correct way to pass a value into a controller on its creation?

Answer Source


This answer is old. This is just a proof of concept on how the desired outcome can be achieved. However, it may not be the best solution as per some comments below. I don't have any documentation to support or reject the following approach. Please refer to some of the comments below for further discussion on this topic.

Original Answer:

I answered this to Yes you absolutely can do so using ng-init and a simple init function.

Here is the example of it on plunker


<!DOCTYPE html>
<html ng-app="angularjs-starter">
  <head lang="en">
    <script src="//"></script>
    <script src="app.js"></script>
  <body ng-controller="MainCtrl" ng-init="init('James Bond','007')">
    <h1>I am  {{name}} {{id}}</h1>


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
    $ = id;
    $ = name; 
    //Based on passed argument you can make a call to resource
    //and initialize more objects

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download