Updating a single item in angular scope object

2019-08-15 07:07发布

问题:

I am creating a like function for pictures on an Ionic app.

I can return a like count and true or false for if the request was to like or unlike a photo.

I have a function on my photos which calls a post action in my controller (the on double tap)

<div ng-repeat="update in updates" class="custom-card">
  <div ng-show="{{update.image}}" class="image">
    <img on-double-tap="likeUpdate({{update.data.id}})" class="full-image" ng-src="https://s3-eu-west-1.amazonaws.com/buildsanctuary/images/{{update.image.name}}" imageonload>
  </div>
  <div class="action-bar">
    <div class="left">
        <i ng-class="liked ? 'ion-ios-heart red' : 'ion-ios-heart-outline'"></i><span>like</span>
    </div>
  </div>

If this was a single update shown, I would simple update the 'update' scope and it would work. But I have a list of photo's shown and the user can double tap on anyone. What I need is to be able to update the scope of updates but only for a single update and not the whole lot.

My function in controller:

$scope.likeUpdate = function(update_id) {
    console.log("clicked");
    $http.post( $rootScope.apiURL + 'likeupdate', {
        update_id : update_id,
        user_id : $rootScope.currentUser.id
    }).success(function(update, response){
       // update the specific ng repeat item scope?
    });
}

Is there an angular way for this?

回答1:

Don't pass the id, pass the whole update into your handler so you can change it inside, something like this:

<img on-double-tap="likeUpdate({{update}})" ... >

And controller:

$scope.likeUpdate = function(update) {
    console.log("clicked");
    $http.post( $rootScope.apiURL + 'likeupdate', {
        update_id : update.data.id,
        user_id : $rootScope.currentUser.id
    }).success(function(result, response){
       update.xxx = ...
    });
}

A simple runnable example:

angular.module('myApp', [])
  .controller('MyController', ['$scope', function($scope) {
     $scope.updates = [{'name':'one', count: 2}, {'name':'two', count:3}];
     $scope.likeUpdate = function(update) {
       // this doesn't work:
       update = {'name': 'test', count: update.count+1};
       // this works:
       update.name = 'test';
       update.count += 1;
     };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyController">
  <div ng-repeat="update in updates" class="custom-card">
    <div ng-click="likeUpdate(update)">{{update.name}} - {{update.count}}</div>
  </div>
</div>