我開始在角種子。我有一個json文件,顯示下面的項目。角度js顯示基於選定項目和url路徑的名稱
{
"id":"1",
"name":"Spain",
"abbrev":"esp"
}
當我點擊列表中的某個國家時,我想顯示該項目的名稱等詳細信息。
我有這個工作如下所示。
/* app.js */
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', ['ngRoute','myApp.controllers','myApp.services'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'templates/view1.html',
controller: 'CountryCtrl'
});
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/:name', {
templateUrl: 'templates/view2.html',
controller: 'CountryCtrl'
});
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/'});
}]);
/* services.js */
angular.module('myApp.services', [])
.factory('Countries', ['$http', function($http) {
var Countries = {};
Countries.name = '';
Countries.listCountries = function() {
return $http.get('../api/countries');
},
Countries.ChangeName = function (value) {
Countries.name = value;
}
return Countries;
}]);
/* controllers.js */
angular.module('myApp.controllers', [])
.controller('CountryCtrl', ['$scope', 'Countries', '$location', function($scope, Countries,$location) {
listCountries();
function listCountries() {Countries.listCountries()
.success(function (data, status, headers, config) {
$scope.countries = data.countries;
})
.error(function(data, status, headers, config) {
$scope.status = 'Unable to load data: ' + error.message;
});
}
$scope.name = Countries.name;
$scope.changeView = function(countryName,indx){
$location.path(countryName);
$scope.name = Countries.ChangeName(countryName);
}
}]);
/* templates/view1.html */
<ul>
<li ng-repeat="country in countries">
<div ng-click="changeView(country.name,$index)">{{country.name}}</div>
</li>
</ul>
/* templates/view2.html */
{{name}}
我不能去工作,如果我去http://www.example.com/app/#/然後導航到西班牙在列表中,然後我得到採取http://www.example.com/app/#/esp和{{名}}被作爲ESP輸出。
但是如果我導航直http://www.example.com/app/#/esp沒有先按一下西班牙的名單我在$ scope.name得不到值
我怎樣才能做到這一點? 我希望名稱也可以根據位置路徑設置,如果可用。 我知道$位置。$$路徑會讓我/ ESP不過我真的不認爲這是使用這個櫃面的URL最好的主意構建出更大的東西如http://www.example.com/app/#/esp/events
我一些如何訪問該項目的索引或ID,這樣我可以再訪問諸如
{{countries[0].name}}
的數據,其中0是ESP ID - 1 什麼是最好的方法?
我真的不明白你的服務是應該做的...... – Tivie 2014-11-04 09:08:10
此外,你必須在你的js代碼的一些錯誤。 '$ scope.status ='無法加載數據:'+ error.message;' - >錯誤未定義。 Theres在「Countries.listCountries」和下一個函數 – Tivie 2014-11-04 09:28:33