嗨,我是新手,学习angular.js。我想从这个url获取数据,这实际上是一个API(http://ba.dev/businesses/businesspage/36),但我不知道如何在controller.js文件中写这个东西。鉴于我的代码,请解释我如何从id = 36的业务中获取数据。
var reControllers = angular.module('reControllers',[]);
reControllers.controller('RecentController', ['$scope','$http' ,function($scope,$http){
$http.get('http://ba.dev/businesses/businesses').success(function(data){
$scope.business = data;
});
}]);
reControllers.controller('PageController', ['$scope','$http', '$routeParams' ,function($scope,$http,$routeParams){
$http.get('http://ba.dev/businesses/businesspage').success(function(data){
$scope.student = data;
$scope.whichItem = $routeParams.itemId;
});
}]);
这是我的app.js文件
var myApp = angular.module('myApp',[
'ngRoute',
'reControllers'
]);
myApp.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/main',{
templateUrl : 'partials/main.html',
controller : 'RecentController'
}).
when('/page/:itemId',{
templateUrl : 'partials/page.html',
controller : 'PageController'
}).
otherwise({
redirectTo: '/main'
});
}]);
答案 0 :(得分:1)
您可以使用$routeParams
$http.get('http://ba.dev/businesses/businesspage/'+ $routeParams.itemId)
此后添加服务器端逻辑,从URL传递itemId
,执行需要的操作以从数据库获取数据并将其返回。
答案 1 :(得分:0)
您应该使用then
代替success
,因为它已被弃用。所以,你的代码应该是:`
$http.get('http://ba.dev/businesses/businesses').then(function(data){
$scope.business = data;
}); }]);.....
来自AngularJS文档:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
有关route params的更多信息:AngularJS $routeParams