我想使用 angularjs 的自定义指令制作一个小部件,但卡在某处注入(inject) $http 服务。
var app = angular.module('app',[]);
app.directive('users',function($scope,$http){
return {
$http.get('https://jsonplaceholder.typicode.com/users')
.then(function(response) {
$scope.user = response.data;
})
}
})
想过怎么办吗?我知道上面的代码不起作用,但我不知道如何继续。
最佳答案
这应该看起来像:
var app = angular.module('app',[]);
app.directive('users', users);
users.$inject = ['$http'];
function users($http){
return {
restrict: 'E', // if it's element
template: '<div><ul><li ng-repeat="user in users">{{user.name}}</li></ul>{{user}}</div>', // example template
link: function($scope){
$http.get('https://jsonplaceholder.typicode.com/users')
.then(function(response) {
$scope.users = response.data;
});
}
};
}
这是一个工作的 jsbin:http://jsbin.com/qepibukovu/1/edit?html,js,console,output
关于javascript - 带有 $http 注入(inject) angularjs 的自定义指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39222242/