简体   繁体   English

角路由/动态内容

[英]Angular Routing/Dynamic Content

I'm trying to find out what the best practice is for dynamic content in an angular app. 我试图找出最佳的做法是在有角度的应用程序中动态内容。 I have an array that contains a set of phone numbers and i want to create a page/view base on the country of the phone numbers. 我有一个包含一组电话号码的数组,我想基于电话号码的国家/地区创建页面/视图。 So all German phone numbers should be listed under #/app/numbers/germany for example. 因此,所有德国电话号码都应列在例如#/ app / numbers / germany下。

The array that holds the phone numbers will be fetched at page load - so it's ready for use and filtration. 包含电话号码的数组将在页面加载时获取-这样就可以使用和过滤了。

Normally I would create a filtration based on the url parameters like ?country=Germany , but I don't suppose this is the right way to do it. 通常,我会根据?country=Germany类的url参数创建过滤条件,但我认为这样做不是正确的方法。

I use a filter for removing duplicates from the view in order to create a list over all countries (which should hold the link to the numbers under each country): 我使用过滤器从视图中删除重复项,以便创建所有国家/地区的列表(该列表应包含指向每个国家/地区下的数字的链接):

.filter('unique', function(){
   return function(collection, keynam){
      var output = [];
          keys = [];
   angular.forEach(collection, function(item){
      var key = item[keyname];
      if(keys.indexOf(key) === -1) {
         keys.push(key);
         output.push(item);
      }
  });
   return output;
 };
})

So basically I want to know what the best practice in this scenario is - using (dynamic) routes, load data based on URL or something entirely different? 因此,基本上我想知道这种情况下的最佳做法是-使用(动态)路由,基于URL加载数据还是完全不同的方法?

Solution

I've found a solution by using $stateParams from the routing. 我已经通过使用路由中的$stateParams找到了一个解决方案。 My dynamic state: 我的动态状态:

.state('app.single', {
 url: '/numbers/:country',
 views: {
   'menuContent': {
     templateUrl: 'templates/country.html',
     controller: 'CountryCtrl'
   }
 }
})

In the controller I assign the $stateParams to a scope variable like this: 在控制器中,我将$stateParams分配给这样的作用域变量:

.controller('CountryCtrl', function($scope, $stateParams, Numbers) {
  //Load Firbase ref and get data
  $scope.numbers = Numbers;
  $scope.currentCountry = $stateParams.country;
})

And finally in the view I use $scope.currentCountry to filter out the numbers that match the current state/route: 最后,在视图中,我使用$scope.currentCountry筛选出与当前状态/路由匹配的数字:

ng-repeat="item in numbers | filter:{Country:currentCountry}"

The great thing about this is that i don't need to load data more than once, but I can rely on controller logic. 很棒的是,我不需要多次加载数据,但是我可以依靠控制器逻辑。

I would load only the data you need: 我只会加载您需要的数据:

At first let's declare an angular route 首先,让我们声明一条角度路线

$routeProvider
        .when('/numbers/:country',{
            templateUrl : '/foo/bar/baz/numbers.html',
            controller : 'NumbersController'
        })

Then in the NumbersController you can use the country parameter to query the backend and fetch the array of numbers related to the requested country 然后,在NumbersController中,您可以使用country参数查询后端并获取与所请求国家/地区相关的数字数组

app.controller("NumbersController",function($scope,$http,$routeParams){
   $http({
    url: "some_url", 
    method: "GET",
    params: {country: $routeParams.country}
   }).success(function(response){
     //Handle the data here
   }).error(function(response){
     //Handle errors here
   });
 });

The first benefit of this approach is that you don't have to load the entire array, but only what you need. 这种方法的第一个好处是您不必加载整个阵列,而只需加载所需的内容。

Furthermore you don't have to do filtering and parsing and other more complex operations. 此外,您不必进行过滤和解析以及其他更复杂的操作。

There is not one single way to solve your problem, but this is a common approach in the angularJS world 没有单一的方法可以解决您的问题,但这是angularJS世界中的一种通用方法

If you have a service (PhoneNumberSvc) with the function "getNumbers(country)" that filters the phone numbers by country: 如果您有一项具有功能“ getNumbers(country)”的服务(PhoneNumberSvc),该服务可以按国家/地区过滤电话号码:

app.module('appName')
.service('PhoneNumberSvc', [
    '$http',
    function ( $http ) {

        this.getNumbers = function ( country ) {
            return $http.get('numbers.json')
                .then(function ( response ) {
                    var return_data = [];
                    angular.forEach(response.data, function ( item ) {
                        if ( item.country = country ) {
                            return_data.push(item);
                        }
                    });
                    return return_data;
                });
        };

    }
]);

Then you could do something like this in your config: 然后,您可以在配置中执行以下操作:

$routeProvider.when('/app/numbers/:country', {
    templateUrl: 'yourview.html',
    controller: 'YourController',
    resolve: {
        data: function ( $route, PhoneNumberSvc ) {
            var country = $route.current.params.country;
            return PhoneNumberSvc.getNumbers(country);
        }
    }
});

Then, in your controller, be sure to inject the parameter "data": 然后,确保在控制器中注入参数“ data”:

angular.module('appName')
.controller('YourController', [
    '$scope',
    'data',
    function ( $scope, data ) {
        $scope.numbers = data;
    }
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM