Angular js显示基于所选项目和url路径的名称

Angular js display name based on selected item and url path

本文关键字:路径 url 项目 js 显示 于所选 Angular      更新时间:2023-09-26

我开始研究有角度的种子。我有一个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 就没有价值

我怎样才能做到这一点?如果位置路径可用,我希望还可以根据位置路径设置名称。我知道$的位置$$path会让我/特别是,但我真的不认为这是最好的主意,以防url扩展到更大的东西,例如http://www.example.com/app/#/esp/events

我能知道如何访问项目的索引或id,这样我就可以访问之类的数据吗

    {{countries[0].name}}

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

伙计,你的应用程序有几个问题。

  • 您的服务虽然仅用于检索信息,但仍保留"状态"
  • 您对两个不同的视图使用相同的控制器(不良做法)
  • $scope.status='Unable to load data: ' + error.message;-->未定义错误
  • 还有一些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);
      }
    );
  }
]);

在您的"CountryCtrl"中,如果您包含$routeParams并使用$routePparams.tlaname,您将可以访问tlaname。然后,您可以使用它来初始化您的数据。