AngularJS路由问题与视图

时间:2015-04-16 18:56:56

标签: javascript angularjs angular-routing

我正在尝试创建一个包含商店列表的单页应用程序,每张商店卡都是指向包含产品表的另一个视图的链接。

一家商店看起来像:

shop = {
  id: 1,
  name: "foo",
  description: 'bar',
  products: [item1, itemn];
};

app.js:

angular
  .module('lightpointTestApp', [
    'ngCookies',
    'ngRoute',
    'ui.sortable'
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/about', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl'
      })
      .when('/products/:shopID', {
        templateUrl: 'views/products.html',
        controller: 'ProductsCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

Main.html查看商店列表在哪里:

<h3>Shop list</h3>
<div class="row shopsContainer" ui-sortable ng-model="shops">

  <div class="col-lg-3 shopCard" ng-repeat="shop in shops">
    <button class="btn close cardClose" ng-click="removeShop($index)">&times;</button>
    <div class="cardNumber">{{ shops.indexOf(shop) + 1 }}</div>
    <div class="cardHeader">{{ shop.name }}</div>
    <div class="cardBody">
      {{ shop.address }}<br />
      {{ shop.hours }}<br />      
      <a href="/#/products/{{ shop.id }}">View {{ shop.products.length }} products</a>
    </div>
  </div>

</div>
<div class="row">
  <input type="text" ng-model="newShop.name" placeholder="Shop name" class="col-lg-3" />
  <input type="text" ng-model="newShop.address" placeholder="Shop address" class="col-lg-3" />
  <input type="text" ng-model="newShop.hours" placeholder="Shop hours" class="col-lg-3" />
  <button class="btn btn-primary col-lg-3" type="button" ng-disabled="!newShop.name || !newShop.address || !newShop.hours" ng-click="addShop()">Add Shop</button>
</div>

</span>
</div>
</div>

products.js - 产品页控制器

angular.module('lightpointTestApp')
  .controller('ProductsCtrl', function ($scope, $routeParams, shops) {
    $scope.shopList = shops;
    $scope.shop = {};

    $scope.getShop = function (id) {
      for (var i = 0; i < $scope.shopList.length; i++) {
        if ($scope.shopList[i].id === id) {
          return $scope.shopList[i];
        }
      }
      return null;
    };

    var shopID = $routeParams.shopID;
    $scope.shop = $scope.getShop(shopID);

  })

products.html包含产品的表格在哪里

<h2>{{ shop.name }}</h2>
  <table class="table table-hover">
    <tr>
      <th>Product Name</th>
      <th>Product Description</th>
    </tr>
    <tr ng-repeat="product in shop.products">
     <td> {{ product.name }} </td>
     <td> {{ product.description }} </td>      
    </tr>
  </table>

问题是products.html没有与products.js绑定,并显示类似{{shop.name}}和空表的内容。

P.S。我认为products.js不正确,但我尽力做好。

感谢。

2 个答案:

答案 0 :(得分:1)

shops中有一个参数ProductsCtrl,但没有任何内容会为其传递值,因此它将为null。您将$scope.shopList的值设置为它,然后尝试迭代NULL数组,以便获得异常。

您可以将shops的值存储在服务中,然后通过注入将其传递到您的应用中。您可以在main.js中或在服务本身内初始化它们的值,然后如果将它们注入ProductsCtrl,则值将可用,如

angular.module('lightpointTestApp')
      .controller('ProductsCtrl', ['$scope', '$routeParams', 'shopsService', 
         function ($scope, $routeParams, shopsService) {
             $scope.shopList = shopService;
             $scope.shop = {};

             $scope.getShop = function (id) {

                for (var i = 0; i < $scope.shopList.length; i++) {
                  if ($scope.shopList[i].id === id) {
                     return $scope.shopList[i];
                  }
                }
                return null;
             };

            var shopID = $routeParams.shopID;
            $scope.shop = $scope.getShop(shopID);

        }]);

shopsService可能看起来像

angular.module('lightpointTestApp')
   .service('shopsService', function() {
       return [ 
                // add whatever fields you need here from code in main.js
                { name: 'shop1', address: 'addr1' },
                { name: 'shop2', address: 'addr2' }
              ];
   });

答案 1 :(得分:0)

您的店铺物品来自哪里?您正在shop.js中传递商店,但未在代码中引用它。您还应该使用$ q来使用异步数据的promises。还可以使用filter()函数而不是for循环来通过shopId查找商店。

您现在正在使用商店的API或存储本地json吗? 对于angular,您应该在工厂或服务中分离数据逻辑操作:

productService.js

angular.module('lightpointTestApp')
  .factory('shopService',function($http, $q){
    var shops = [];
    return {
      getShops: function () {
        var deferred = $q.defer();
        $http.get('<path to product.json or api>').success(function(data){
          shops = data;
          deferred.resolve(data);
        }) 
        return deferred.promise;
      },
      getShopById: function(shopID) {
        var deferred = $q.defer();
        deferred.resolve(shops.filter(function(chain){
          return chain.id === shopID;
        })[0]);
        return deferred.promise;
      }
    } 
  });

product.js

angular.module('lightpointTestApp')
 .controller('ProductsCtrl', function ($scope, $routeParams, $q,shopService) {
    $scope.shopList = [];
    $scope.shop = {};
    var shopID = $routeParams.shopID;

    shopService.getShops.then(function(shops){
      $scope.shopList = data;    
    })

    $scope.getShopById = function(shopID) {
      shopService.getShopById(shopID).then(function(shop){
      $scope.shop = shop;
     });
    }
  });