数组没有改变

时间:2016-01-01 22:40:51

标签: angularjs

所以我是角度JS的新手,我在编辑数组中的一个对象时遇到了问题。下面的喜欢函数被调用,并且相应的对象也被传递给它。循环甚至找到正确的对象并将其喜欢的值设置为true。但是出于某种原因,当我第二次点击喜欢的按钮时,它仍然显示喜欢的值为false ...我确信它的东西非常简单。

<div class="thelist" data-ng-repeat="b in data| orderBy:choice">
                    <h2>{{ b.from }}</h2>
                    <p>{{b.date}}</p>
                    <img class="full-image" src="{{b.img}}">
                    <p>{{b.content}}</p>
                    <p>{{b.likes}}</p>
                    <button class="tab-item" ng-click="liked({{b}})"></button>

            </div>

App.js:

ref.on("child_added", function (snapshot) {
                var newPost = snapshot.val();
                $scope.data.push({

                    content: newPost.content,
                    date: newPost.date,
                    from: newPost.from,
                    img: newPost.img,
                    likes: newPost.likes,
                    realdate: newPost.realdate,
                    id: snapshot.key(),
                    liked: false

                });

            }); 

喜欢的功能:

        $scope.liked = function (post) {

         if (post.liked == false){
                    console.log("liked has been run");
                    angular.forEach($scope.data, function (object) {

                    if (object.id == post.id) {

                        object.liked = true;

                    }

                });

  //add 1 like on server here        

           }

  }

2 个答案:

答案 0 :(得分:2)

您不得在ng-click中使用模板。变化

<button class="tab-item" ng-click="liked({{b}})"></button>

<button class="tab-item" ng-click="liked(b)"></button>

答案 1 :(得分:0)

要扩展@ hege_hegedus的答案,&#34; ng-click&#34; directive接受一个表达式(可以访问$ scope变量的javascript表达式)。从那以后它需要一个表达式并且可以完全访问$ scope,你可以想到

<button class="tab-item" ng-click="liked(b)"></button>

作为

<button class="tab-item" ng-click="$scope.liked($scope.b)"></button>