Mawg
Mawg

Reputation: 40155

Using a scope variable to index a scope array in ng-repeat?

I have a tree like structure, received as JSON from some PHP code which I wrote for my server.

The code is far to complex to post, so let's use an example:

A company has

So, I can find myself with something like

$scope.departments[1].jobs[1].people[1]
$scope.departments[1].jobs[1].people[2]

etc

I have $scope variable for the current user-selected department, job and person.

My problem is where I want to use an ng-repeat of the jobs in the HTML view for the jobs.

The statement

<div ng-repeat="job in departments[{{departmentId}}].jobs>

gives Error: [$parse:syntax], as does

<div ng-repeat="job in departments[$scope.departmentId].jobs>

(which I tried in desperation).

What is the correct syntax?

I am wondering if I will need to try

<div ng-repeat="job in GetJobsForCurrentDepartment()>  

since $scope.departmentId would be in scope in my controller, but is not in the HTML view for the departments.

Upvotes: 1

Views: 884

Answers (2)

Vivek
Vivek

Reputation: 13298

Since a view has a controller associated with it, and controller has a $scope associated with it. It is not required to use $scope the html element for referencing the variables defined in the controller. Any variable used with a element in a view is looked up in the scope associated with that element. $scope is required only in the script.

Thus you can write

<div ng-repeat="job in departments[departmentId].jobs>

This will fetch the value of departmentId & jobs inside it will be processed by the ng-repeat directive.

Upvotes: 2

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

You don't have to mention $scope attached with a varable in view

try like this

<div ng-repeat="job in departments[departmentId].jobs>

JS

$scope.departmentId=1;

Upvotes: 1

Related Questions