I'm creating an angular app with a rails backend and accessing the database through api calls and receiving a json object. I'm having trouble with defining multiple scoped variables within a controller. I'm currently returning a variable markets which contains all markets in the database - this is my index. I'm also trying to access a single market for the show page and this is where I'm having trouble. Initially I had 2 separate controllers which worked but didn't seem correct.
Thanks!
Routes:
angular.module('farmCart', ['ui.router', 'templates'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home/_home.html',
controller: 'mainCtrl',
})
.state('markets', {
url: '/markets',
templateUrl: 'markets/_markets.html',
controller: 'marketsCtrl',
resolve: {
marketsPromise: ['markets', function(markets) {
return markets.getAll();
},
],
},
})
.state('market', {
url: '/markets/{id}',
templateUrl: 'markets/_market.html',
controller: 'marketsCtrl',
resolve: {
market: ['$stateParams', 'markets', function($stateParams, markets) {
return markets.get($stateParams.id);
},
],
},
})
.state('booths', {
url: '/booths/{id}',
templateUrl: 'booths/_booths.html',
controller: 'boothsCtrl',
resolve: {
booth: ['$stateParams', 'booths', function($stateParams, booths) {
return booths.get($stateParams.id);
},
],
},
});
$urlRouterProvider.otherwise('home');
},
]);
Markets Factory:
angular.module('farmCart')
.factory('markets', [
'$http',
function($http) {
var o = {
markets: [],
};
o.getAll = function() {
return $http.get('/markets.json').success(function(data) {
angular.copy(data, o.markets);
});
};
o.get = function(id) {
return $http.get('/markets/' + id + '.json').then(function(res) {
return res.data;
});
};
return o;
},
]);
Markets Controller:
angular.module('farmCart')
.controller('marketsCtrl', [
'$scope',
'markets',
function($scope, markets) {
$scope.markets = markets.markets;
$scope.market = markets.markets.id;
},
]);
Your resolves are named marketsPromise
and market
, none of which you're actually injecting into your controller. I'd recommend you use two controllers since it seems like the two states have separate purposes.
angular.module('farmCart')
.controller('marketsCtrl', [
'$scope',
'marketsPromise',
function($scope, marketsPromise) {
$scope.markets = marketsPromise;
},
]);
angular.module('farmCart')
.controller('marketCtrl', [
'$scope',
'market',
function($scope, market) {
$scope.market = market;
},
]);
Also, you may want to reconsider the name of the marketsPromise
resolve, because ui-router will inject the data itself, not the promise, which may lead to confusion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.