简体   繁体   中英

I can't edit a object in an array, ng-model doesn't change with ng-click

I am making a movie library. I use ng-repeat to show the movies and, for each movie there is a button to edit it and another one to remove it. The remove button works just fine, but the edit button doesn't. It should open a panel and fill it with the movie data, but it only opens the panel with the first value I defined for the index.

button
<i class="glyphicon glyphicon-pencil small btnEdit" ng-click="i =(movies.indexOf(movie));"></i>

input
<input type="text" class="form-control" placeholder="Title" id="title" ng-model="movies[i].title">

the whole code is here: https://jsfiddle.net/victoorns/mwgcnsno/2/

Your controller's $scope property 'i' is being hidden via the rules behind scope inheritance. Ng-repeat creates its own isolate scope and since 'i' is a primitive (its just an integer), 'i' is only being set on that child $scope, as opposed to the main parent controller's scope.

<input type="text" class="form-control" placeholder="Title" id="title" 
       ng-model="movies[selected.movieIndex].title">

<i class="glyphicon glyphicon-pencil small btnEdit" 
   ng-click="selected.movieIndex =(movies.indexOf(movie));"></i>

Heres an updated jsfiddle here .

Notice how I am using an object (selected.movieIndex) so that is correctly updating the right property.

Heres more on understanding the exact behavior going on with the scope here

Approach is putting too much business logic in the view.

Pass whole object back to controller when you do things like this. Then do any splicing, copying etc in controller:

Simplified example:

<div ng-repeat="movie in movies">
  <button ng-click="edit(movie)">
  <button ng-click="delete(movie)">
</div>

In controller:

  $scope.delete = function(movie){
    var idx = $scope.movies.indexOf(movie);
    if(idx !=-1){      
       $scope.movies.splice(idx,1)
    }
  }

  $scope.edit = function(movie){
     $scope.selectedMovie = movie;
  }

Also get rid of all the jQuery and get rid of bootstrap.js and replace with angular-ui-bootstrap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM