0 votes
1 view
in Web Technology by (47.8k points)

I have a controller responsible for communicating with an API to update properties of a user, name, email, etc. Each user has an 'id' 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 ng-controller. For example:

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

$scope.connection = $resource('api.com/user/' + id)


and in the HTML

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

where {% 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?

1 Answer

0 votes
by (107k points)

Below is the way that you can use to pass parameter to an AngularJS controller on creation:-

app.controller('modelController', function($scope, $attrs) { 

if (!$attrs.model) throw new Error("No model for modelController"); 

$scope.url = "http://example.com/fetch?model="+$attrs.model; 


<div ng-controller="modelController" model="foobar"> 

  <a href="{{url}}">Click here</a> 


Welcome to Intellipaat Community. Get your technical queries answered by top developers !