我创建了一个Angular工厂,然后在控制器中使用它。工厂包含一个我试图在控制器中使用的delete
方法,但是,我看到一个错误,指出未定义index
。以前,在我拥有工厂之前,当控制器中的所有内容都在工作时,此功能有效,但现在不再定义index
。我在这里已经阅读了很多答案,但是找不到答案。
我的代码如下所示:
js
app.factory('addressFactory', function(){
var addressFactory = {};
addressFactory.addressBook = [];
addressFactory.deleteAddress = function(index) {
addressFactory.addressBook.splice(index, 1);
localStorage.setItem('addressBook', JSON.stringify(messages.addressBook));
}
return addressFactory;
})
.controller('testCtrl', ['$uibModal', 'addressFactory', function ($uibModal, addressFactory) {
this.addressBook = addressFactory.addressBook;
this.deleteAddress = addressFactory.deleteAddress(index);
}]);
html
<div ng-repeat="contact in ctrl.addressBook track by $index">
<p>{{contact.name}}</p>
<button ng-click="ctrl.deleteAddress($index)">Delete Contact</button>
</div>
最佳答案
改变这个
this.deleteAddress = addressFactory.deleteAddress(index);
对此:
this.deleteAddress = function(index){
addressFactory.deleteAddress(index);
};