我对 Angular 很陌生,我有一个关于在指令中使用 $http 和 $location 的愚蠢问题。我正在创建一个待办事项列表,并希望在单击链接时删除一个条目。
目前,我已在<a>
上设置了属性指令并希望它在单击时对我的 api 进行删除调用(我在想如果我要在主干中执行此操作,则类似于绑定(bind)单击事件,这会触发调用以从集合中删除模型,并且我有点相应地构建我的代码?)
指令
app.directive('delete', function() {
return {
link: function(scope, element, attrs) {
element.bind('click', function(event) {
scope.$apply(function() {
$http.delete('/api/posts/' + $routeParams.id).
success(function(data) {
$location.path('/app')
})
})
})
}
}
})
Controller
app.controller('IndexCtrl', ['$scope', '$http', '$location'
function($scope, $http, $location) {
$http.get('/api/posts').
success(function(data) {
$scope.posts = data.posts;
})
}
]);
标记
div(ng-controller='IndexCtrl')
h1 Blog
div
a.btn(href='/app/newpost') New Post
ul
li(ng-repeat='post in posts')
a(href='/app/{{ post._id }}')
h3 {{ post.title }}
div {{ post.text }}
a(href='/app/editpost/{{ post._id }}') Edit
a(href='#', delete id='{{post._id }}') Delete
最佳答案
app.directive('delete',['$http', '$location',function($http, $location) {
//your code ..
}]);
与 Controller 的 DI 操作相同
关于javascript - 如何在指令中使用 $http 和 $location?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17003020/