JP.
JP.

Reputation: 5594

Watching for changes since original with an AngularJS model

If I have a database object, which is loaded via JSON within my Angular App I would use a structure something like this:

Data

{
  "colours": ["red","yellow","pink","green","purple","orange","blue"]
}

Controller

angular.module('MyApp').controller('Page_controller',function($scope,$http) {
  $scope.addColour = function(e) {
    $scope.data.colours.push('')
  };

  $scope.removeColour = function(e) {
    var colour_index = $scope.data.colours.indexOf(the_colour_name);
    $scope.data.colours.splice(colour_index,1);
  }

  $http.json("/database/query.json").success(function(data) {
    $scope.data = data;
  })
})

/views/display.html

<div>
  <ul>
    <ng-include="'/templates/colour.html'" ng-repeat="colour in data.colours"></ng-include>
    <li><a href="" ng-click="addColour()" required>Add a colour</a></li>
  </ul>
  <div id="correct">CORRECT</div>
</div>

/templates/colour.html

<li><input type="text" ng-model="colour" placeholder="Name of colour"></input> <a href="" ng-click="removeColour(some_way_to_refer_to_this_colour)">X</a></li>

Now I can add colours to a list and remove them. (Yes the removing them is a little blagged above, I assume you can all see what I'm trying to do though!)

My question is: How can I have the #correct div showing only if the colours are the ones originally loaded?

Upvotes: 0

Views: 319

Answers (1)

Mark Rajcok
Mark Rajcok

Reputation: 364747

Copy your colours array to some other scope variable, e.g., $scope.originalColours.

Add ng-show to your HTML:

<div ng-show="showCorrect">CORRECT</div>

Add a watch to your controller:

$watch('data.colours', function() {
    if($scope.data.colours.length === $scope.originalColours.length) {
        // Compare arrays $scope.data.colours and $scope.originalColours.
        // If the two arrays are the same, set $scope.showCorrect
        // to true and return.
    }
    $scope.showCorrect= false;
}, true);

Upvotes: 1

Related Questions