gpt4 book ai didi

angularjs - 在 Angular 中修改数组不起作用

转载 作者:行者123 更新时间:2023-12-02 02:57:56 27 4
gpt4 key购买 nike

我得到$scope.persons从后端。我使用 ng-repeat 列出它。

为什么在我的情况下,当 $scope.openDeleteModal 时数组不会被修改叫做?

该函数被调用,但 $scope.persons. 没有任何反应为什么?

application.controller('listPersonController', function ($scope, personService) {
personService.getPersons()
.then(function(persons) {
$scope.persons = persons;
});

$scope.openDeleteModal = function (personId, firstname, lastname, index) {
console.log("click " + $scope.persons.length);
$scope.persons.splice();
console.log("click " + $scope.persons.length);
};
});

编辑:

好吧,我忘记了拼接。我用这个代替

 $scope.openDeleteModal = function (personId, firstname, lastname, index) {
console.log("click " + $scope.persons.length);
$scope.persons = [];
console.log("click " + $scope.persons.length);
};

第一个记录 3。第二个记录 0。但我没有看到范围(ng-repeat)有任何变化。

HTML:

<tbody>
<tr ng-repeat="p in persons">
<td>{{p.firstname}}</td>
<td>{{p.lastname}}</td>
<td><a href="#/register_person/{{p.id}}" class="tiny button radius" >Edit</a></td>
<td>
<a href="#"
ng-click="openDeleteModal(p.id, p.firstname, p.lastname, $index)"
class="tiny button alert radius">Delete</a>
</td>
</tr>
</tbody>

服务:

personService.getPersons = function($scope){
var promise = $http.get("rest/person").then(function (response) {
return response.data;
});
return promise;
};

这就是{{persons}}就在 Controller 下方给出

[{"id":"5331c6f33004e1c8a26492a8","名字":"卡尔","姓氏":"斯文森"},{"id":"5331dfdb3004e1c8a26492ad","名字":"珍妮","姓氏":"Bertilsson"},{"id":"5331ee4e3004e1c8a26492ae","firstname":"Bosse","lastname":"Gustavsson"}]

当我修改范围时,这也不会改变

编辑尝试进一步简化事情。

application.controller('listPersonController', function ($scope, personService) {

var personsList = [{"id":"5331dfdb3004e1c8a26492ad","firstname":"Johnny","lastname":"Bravo"}];

$scope.persons = personsList;

$scope.openDeleteModal = function (personId, firstname, lastname, index) {
console.log("click " + $scope.persons.length);
$scope.persons.length = 0;
personsList.length = 0;
console.log("click " + $scope.persons.length);
};
});

编辑: html 现在非常简单

<div class="row" ng-controller="listPersonController" >
<p ng-repeat="p in persons">{{p.firstname}} <a href="#" class="tiny button alert radius" ng-click="openDeleteModal(p.id, p.firstname, p.lastname, $index)" >Delete</a></p>
</div>

更简单。 var的值在我的页面上是 3,点击后不会更新。

application.controller('listPersonController', function ($scope, personService) {

$scope.var = "1";

$scope.openDeleteModal = function () {
$scope.var = "2";
};

$scope.var = "3";
});

编辑:ng-view 移出时,代码可以按预期工作。 。为什么会发生这种情况?

最佳答案

从链接中删除 href="#",它可能会导致页面导航到自身并导致 Controller 被重新实例化。

关于angularjs - 在 Angular 中修改数组不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22646070/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com