0

For example, I need to apply some CSS rule to one element of collection that is meant to be selected.

<div ng-repeat="fragments" ng-click="makeSelected()"></div>

$scope.fragments = [
   {id: 6379, someProperty: "someValue" },
   {id: 8934, someProperty: "someValue" },
   {id: 1654, someProperty: "someValue" },
   {id: 5654, someProperty: "someValue" }
];
$scope.selectedFragmentId = 6379;

The obvious implementation of makeSelected function is to attach a class name selected to div that was clicked then launch a loop through other elements and remove class name selected from them.

Also I need to "select" the particular div without clicking on them, only by passing id of selected fragment in some function. Obviously, this function also must have a loop that will go through fragments and will compare selectedFragmentId with every fragment ids.

My approach looks ok, but I have a bad feeling that it is so imperative instead of declarative. This is not the way in the spirit of angularjs. So, here is a question: is there a way to implement my functionallity in declarative way, without using loops?

1 Answer 1

1

You don't need any loops.

<div ng-class="{selected: fragment.id == selectedFragmentId}" ng-repeat="fragment in fragments" ng-click="makeSelected()"></div>

Then, if you set $scope.selectedFragmentId, div for selected fragment automatically set class to selected

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.