Umar Umar - 2 months ago 5
AngularJS Question

Update a model value and update DOM from button in ng-repeat

I have a button for each website state which shows state of each website on server (stopped or started).

The buttons are basically being treated as switcher so i can update value of state variable for each element of model.

<tr ng-repeat="website in model">
<td>{{website.Name}}</td>
<!-- website state can have either value **stopped** or **started** -->
<td>
<i class="fa fa-toggle-on active"ng-if="website.State == 'Started'" ng-model="website" ng-click="changeStatus(website)">
</i>
<i class="fa fa-toggle-on fa-rotate-180 inactive" ng-if="website.State == 'Stopped'" ng-model="website" ng-click="changeStatus(website)">
</i>
</tr>


controller :

$scope.changeStatus = function (x) {
alert(x.Name);
//$scope[x].State == 'Stopped'


//if ($scope.State== 'Started')
// $scope.State = "Stopped";
//else
// $scope.State = "Started";
}


Requirement :

I need to update value if it is stopped than change it to start and vice versa.

So farth I could not find any solution. The alert Statement works fine. But I need to update model and the model should be bind to the element in html. So that when I change the button from "start" to "stop", model value should also be changed and hence button should go from start to stop on the basis of ng-if

Answer
  • ng-model for <i> will not work
  • there opened but not closed <td> element in your example
  • argument you pass to changeStatus function is an object. So it is passing by reference.

angular.module('models', []).controller('websites',
  function($scope) {
    $scope.websites = [{
      Name: 'foo',
      State: 'Started'
    }, {
      Name: 'bar',
      State: 'Stoped'
    }];
  
  
    $scope.changeState = (website) => {
       if (website.State == 'Started') {
         website.State = 'Stoped';
       } else {
          website.State = 'Started';
       }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="models" ng-controller="websites">
  <div ng-repeat="website in websites">
    <h1>{{ website.Name }}</h1>
    <button ng-click="changeState(website)">
      {{ website.State }}      
    </button>
    
    <button ng-if="website.State == 'Stoped'" ng-click="changeState(website)">
      Stoped
    </button>
    
    <button ng-if="website.State == 'Started'" ng-click="changeState(website)">
      Started
    </button>
  </div>
</div>

Comments