角度js根据所选项目和URL路径显示名称

时间:2014-11-04 08:34:10

标签: javascript angularjs angularjs-scope

我开始使用有角度的种子。我有一个json文件,显示如下所示的项目。

{
    "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,{{name}}将输出为esp。

但是如果我直接导​​航到http://www.example.com/app/#/esp而没有先点击列表中的西班牙,我的$ scope.name

就没有价值

我怎样才能做到这一点? 我希望也可以根据位置路径设置名称(如果可用)。 我知道$ location。$$路径会得到我/ esp但是我真的不认为这是最好的想法使用这个url建立更大的东西,例如http://www.example.com/app/#/esp/events

我可以如何访问项目的索引或ID,以便我可以访问像

这样的数据
    {{countries[0].name}}

其中0是esp - 1的id。 什么是最好的方法?

2 个答案:

答案 0 :(得分:2)

Mate,你的应用程序存在一些问题。

  • 您的服务保留“状态”,但仅用于检索信息
  • 您使用相同的控制器来处理2种不同的观点(不良做法)
  • $ scope.status = 'Unable to load data: ' + error.message; - &gt;错误未定义
  • 还有一些js错误,比如迷路的逗号和内容

无论如何,这是您的代码的修订版本。 Fiddle


// Instantiate your main module
var myApp = angular.module('myApp', ['ngRoute']);

// Router config
myApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'templates/view1.html',
        controller: 'CountryListCtrl'
      })
      .when('/:id', {
        templateUrl: 'templates/view2.html',
        controller: 'CountryCtrl'
      })
  }
]);

// Your Factory. Now returns a promise of the data.
myApp.factory('Countries', ['$q',
  function($q) {
    var countriesList = [];

    // perform the ajax call (this is a mock)
    var getCountriesList = function() {
      // Mock return json
      var contriesListMock = [{
        "id": "0",
        "name": "Portugal",
        "abbrev": "pt"
      }, {
        "id": "1",
        "name": "Spain",
        "abbrev": "esp"
      }, {
        "id": "2",
        "name": "Andora",
        "abbrev": "an"
      }];
      var deferred = $q.defer();
      if (countriesList.length == 0) {
        setTimeout(function() {
          deferred.resolve(contriesListMock, 200, '');
          countriesList = contriesListMock;
        }, 1000);
      } else {
        deferred.resolve(countriesList, 200, '');
      }
      return deferred.promise;
    }

    var getCountry = function(id) {
      var deferred = $q.defer();
      if (countriesList.length == 0) {
        getCountriesList().then(
          function() {
            deferred.resolve(countriesList[id], 200, '');
          },
          function() {
            deferred.reject('failed to load countries', 400, '');
          }
        );
      } else {
        deferred.resolve(countriesList[id], 200, '');
      }
      return deferred.promise;
    }

    return {
      getList: getCountriesList,
      getCountry: getCountry
    };
  }
]);


//Controller of home page (pretty straightforward)
myApp.controller('CountryListCtrl', ['$scope', 'Countries',
  function($scope, Countries) {
    $scope.title = 'Countries List';
    $scope.countries = [];
    $scope.status = '';

    Countries.getList().then(
      function(data, status, headers) { //success
        $scope.countries = data;
      },
      function(data, status, headers) { //error
        $scope.status = 'Unable to load data:';
      }
    );
  }
]);

// controller of Country page
// Notice how we use $routeParams to grab the "id" of our country from the URL
// And use our service to look for the actual country by its ID.
myApp.controller('CountryCtrl', ['$scope', '$routeParams', 'Countries',
  function($scope, $routeParams, Countries) {
    $scope.country = {
      id: '',
      name: '',
      abbrev: ''
    };
    var id = $routeParams.id;

    Countries.getCountry(id).then(
      function(data, status, hd) {
        console.log(data);
        $scope.country = data;
      },
      function(data, status, hd) {
        console.log(data);
      }
    );
  }
]);

答案 1 :(得分:-2)

在你的&#34; CountryCtrl&#34;中,如果你包含$ routeParams并使用$ routeParams.tlaname,你将有权访问tlaname。然后,您可以使用它来初始化数据。