lundi 27 mars 2017

AngularJS mg-repeat items with checkbox preventing default on cancelled confirmation

I am using angular (first version) and I having trouble trying to accomplish a task. I have a list of item that I retrieve from the server DB. I am listing those items in a HTML table. There's a Boolean field that I want to update dynamically when the user check or uncheck a checkbox. The problem is during the confirmation. When I cancel the confirmation the check if still retaining its state (check/uncheck) and not going back to its previous state. I tried using "preventDefault", it didn't work. I tried "refreshing" the item array so the view might refresh the data, it didn't work. Here's a fiddle with a representation of what I have: Fiddle

<div ng-app ng-controller="demoController">
  <h3>
    <span class="status"></span>
  </h3>
  <h2>
    Movies i've seen
  </h2>
  <table>
    <tr>
      <th>Name</th>
      <th>Have I seen it?</th>
    </tr>
    <tbody>
      <tr ng-repeat="movie in movies">
        <td> </td>
        <td style="text-align: center">
          <input value=" " type="checkbox" ng-checked="movie.seen" ng-click="confirmSeen(this, $index)" /> </td>
      </tr>
    </tbody>
  </table>
</div>



 function demoController($scope) {
  $scope.status = "AngularJS is up";
  $scope.confirmSeen = function(e, idx) {
    var movie = $scope.movies[idx];
    if (movie !== undefined) {
        var msg = "";
      if(movie.seen) {
        msg = "Are you sure you want to mark " + movie.name + " as unseen?";
      } else {
        msg = "Are you sure you want to mark " + movie.name + " as seen?";
      }

      if (confirm(msg)) {
        movie.seen = !movie.seen;
        $scope.movies.splice(idx, 1, movie);
      } else {
        $scope.movies.splice(idx, 1, movie);
        e.stopImmediatePropagation();
        e.preventDefault();
      }
    } else {
      e.stopImmediatePropagation();
      e.preventDefault();
    }
  }
  $scope.movies = [{
    name: "Conan",
    seen: false
  }, {
    name: "Scarface",
    seen: true
  }, {
    name: "GhostBuster",
    seen: false
  }, {
    name: "The Shawshank Redemption",
    seen: true
  }, {
    name: "Goodfellas",
    seen: true
  }, {
    name: "Life",
    seen: false
  }];
}




Aucun commentaire:

Enregistrer un commentaire