gpt4 book ai didi

javascript - 如何从服务中删除 $scope 对象

转载 作者:行者123 更新时间:2023-12-03 09:20:54 25 4
gpt4 key购买 nike

是否可以从 service() 函数中删除 $scope.contacts 对象?

var module = angular.module('app', []);
module.service('ContactService', function() {
//contacts array to hold list of all contacts
this.delete = function(item) {
console.log(item);
var confirmDelete = confirm("Do you really need to delete " + item.name + " ?");
if (confirmDelete) {
var curIndex = $scope.contacts.indexOf(item);
$scope.contacts.splice(curIndex, 1);
}
}
});
module.controller('ContactController', function($scope, ContactService) {
$scope.contacts = [{
id: 0,
'name': 'Viral',
'email': 'hello@gmail.com',
'phone': '123-2343-44'
}];
$scope.delete = function(id) {
ContactService.delete(id);
if ($scope.newcontact.id == id) $scope.newcontact = {};
}
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ContactController" class="container">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in contacts">
<td>{{ contact.name }}</td>
<td>{{ contact.email }}</td>
<td>{{ contact.phone }}</td>
<td> <a href="javascript:void(0)" ng-click="edit(contact.id)">edit</a> | <a href="javascript:void(0)" ng-click="delete(contact)">delete</a>
</td>
</tr>
</tbody>
</table>
</div>

最佳答案

这是没有意义的,因为服务是单例(每个应用程序存在一个),而您可以拥有多个 Controller 。如果服务可以获取范围,它如何知道它获取了正确的范围!

您可以通过将 $scope 传递到删除函数中来完成此操作,例如

this.delete = function($scope, item)

ContactService.delete($scope, id)

关于javascript - 如何从服务中删除 $scope 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31841569/

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