Umar Umar - 1 month ago 4x
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">
<!-- website state can have either value **stopped** or **started** -->
<i class="fa fa-toggle-on active"ng-if="website.State == 'Started'" ng-model="website" ng-click="changeStatus(website)">
<i class="fa fa-toggle-on fa-rotate-180 inactive" ng-if="website.State == 'Stopped'" ng-model="website" ng-click="changeStatus(website)">

controller :

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

//if ($scope.State== 'Started')
// $scope.State = "Stopped";
// $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

  • 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=""></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 ng-if="website.State == 'Stoped'" ng-click="changeState(website)">
    <button ng-if="website.State == 'Started'" ng-click="changeState(website)">