Question

Question: Is there a proper way of changing the value of an attribute of dom from on to off without doing it in the controller and how can i change it because my code below change all the state even though I only clicked one element?

JSON:

sections = {"data": [{
    "label": "somelabel 1",
},{
    "label": "somelabel 2",
}]};

HTML:

<ul ng-repeat="data in sections.data">
    <a href="" ng-click="do_this ()" data-state="{{! state }}" >{{! data.label }}</a>
</ul>

JS:

var module = angular.module('sidebar_module', []);
module.controller('Menu2Ctrl', ['$scope',
     $scope.state = 'off';
     $scope.do_this = function(){
         if ($scope.state == 'off') {
             dosomething();
             $scope.state = 'on';
         } else {
             dosomething();
             $scope.state = 'on';
         }
     }
]);
Was it helpful?

Solution

The correct way is to have all your javascript in JS files, which essentially means controllers, services etc. Not in HTML.

You have one $scope.state variable, and use that to be display the status of all sections. So the result you get is what exactly you wrote in your program :).

If you want each section to maintain their states separately, you can include the state property in sections object as follows,

sections = {"data": [{
    "label": "somelabel 1", state:'on'
},{
    "label": "somelabel 2", state:'off'
}]};

In the do_this(), take the $index and set the state of the section,

$scope.do_this = function(index){
         var section = sections.data[index];
         if (section.state == 'off') {
             dosomething();
             section.state = 'on';
         } else {
             dosomethingElse();
             section.state = 'on';
         }
     }

In your html you will need to pass the index for do_this

<a href="" ng-click="do_this($index)" data-state="{{!state}}" >{{!data.label}}</a>

Info on ngRepeat and $index

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top