角度在阵列拼接后没有更新dom

时间:2016-06-13 15:23:19

标签: javascript angularjs angularjs-directive angularjs-scope

我有一个控制器,它有测试数组,我已经添加了2个对象。当我从html ng-click调用delete函数时,数组不会在dom中更新,但我可以看到数组是用js代码拼接的。我已经尝试了$ apply(),但这不起作用,因为它已经应用了。

app.controller('HomeCtrl', ['$rootScope', '$scope', function($rootScope, $scope) {

    var person1 = {firstName:"John", lastName:"Doe", age:46}; 
    var person2 = {firstName:"Joe", lastName:"Horn", age:66}; 
    $scope.test = []; 
    $scope.test.push(person1);
    $scope.test.push(person2);

    $scope.deletePost = function(value, post){       
            $scope.test.splice(0, 1);
    }
}]);

HTML:

<div class="row" ng-controller="HomeCtrl">
 <div ng-repeat="tes in test">{{tes.age}}<br></div>
</div>
 <a data-toggle="modal" ng-click="deletePost(value, post)" data-target="#deleteModal"  ng-show="post.user.email == user.email" style="font-size:15px;margin-left: 1rem;" class="card-link" href="javascript:void(0)">Delete</a>

2 个答案:

答案 0 :(得分:1)

你需要重新安排你的dom,你也应该根据索引进行拼接。

尝试:

DOM:

<div class="row" ng-controller="HomeCtrl">
 <div ng-repeat="tes in test track by $index">{{tes.age}}<br></div>
 <a data-toggle="modal" ng-click="deletePost($index, tes)" data-target="#deleteModal"  ng-show="post.user.email == user.email" style="font-size:15px;margin-left: 1rem;" class="card-link" href="javascript:void(0)">Delete</a>
</div>

控制器:

app.controller('HomeCtrl', ['$rootScope', '$scope', function($rootScope, $scope) {

    $scope.test = [{firstName:"John", lastName:"Doe", age:46}, {firstName:"Joe", lastName:"Horn", age:66}]; 

    $scope.deletePost = function(ind, post){       
            $scope.test.splice(ind, 1);
    }
}]);

答案 1 :(得分:0)

在已连接控制器的元素内移动<a>

<div class="row" ng-controller="HomeCtrl">
 <div ng-repeat="tes in test">{{tes.age}}<br></div>
 <a data-toggle="modal" ng-click="deletePost(post, value)" data-target="#deleteModal"  ng-show="post.user.email == user.email" style="font-size:15px;margin-left: 1rem;" class="card-link" href="javascript:void(0)">Delete</a>
</div>