Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k 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 (106k 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> 

</div>

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...