我正在尝试使用ui-router的解析功能,而不是将服务的返回值附加到控制器中(到$ scope),但我被卡住了。
这是我的插件 http://plnkr.co/edit/m94IqBpgbEjtuLBhQVB6?p=preview
HTML
<!doctype html>
<html lang="en" ng-app="restprac">
<head>
<meta charset="UTF-8">
<title>REST!</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-resource.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ui-view></div>
</body>
</html>
image.html
<img ng-src="{{image}}">
的Javascript
var app = angular.module('restprac', ['ngResource', 'ui.router']);
app.config(['$stateProvider', function($stateProvider) {
$stateProvider.state("singleImage", {
url: "/",
templateUrl: image.html,
resolve: {
Image: 'Image',
imageResource: function(Image) {
return imageResource.query().$promise;
}
},
controller: 'ImageController'
});
}]);
app.factory('Image', ['$http', function($http) {
return $http.get('https://httpbin.org/image');
}]);
app.controller('ImageController', ['$scope', 'Image', function($scope, Image) {
$scope.image = Image;
}]);
答案 0 :(得分:1)
有很多问题:
templateUrl
; imageResource
属性无用,不在任何地方使用,并使用未定义的imageResource
变量; https://httpbin.org/image
指向实际图片,并且您尝试将该图片用作src
标记的img
属性,该标记需要网址,而不是图片; 这是一个经过修改的plunkr:http://plnkr.co/edit/uCXDOBEFNyaYkuIegY0N?p=preview
var app = angular.module('restprac', ['ui.router']);
app.config(['$stateProvider', function($stateProvider) {
$stateProvider.state("singleImage", {
url: "/",
templateUrl: 'template.html',
resolve: {
imageUrl: 'image',
},
controller: 'ImageController'
});
}]);
app.run(function($location) {
$location.path('/');
});
app.factory('image', ['$http', function($http) {
return $http.get('imageUrl.txt').then(function(response) {
return response.data;
});
}]);
app.controller('ImageController', ['$scope', 'imageUrl', function($scope, imageUrl) {
$scope.imageUrl = imageUrl;
}]);