AngularJS绑定数据从ngrepeat中的Async Call返回

时间:2013-09-05 14:52:14

标签: angularjs angularjs-ng-repeat angularjs-factory

我有一个index.html文件,我将其用作带有标题,ngview指令和页脚的布局/模板。我在ngview中呈现的视图上成功使用'resolve'属性以在异步调用完成后显示数据,但我正在尝试将主index.html文件中的标题中的导航栏链接到另一个控制器使用异步调用返回的值填充。我好像有两个问题。

  1. 为什么我工厂的数据不会“绑定”到ngrepeat,以便在数据可用时更新视图。
  2. 如何在index.html文件本身上实现解析?我认为在“/”路径上有一个解决方案需要在渲染页面之前加载解析中的所有数据,但我想这只是针对ngview组件中的任何内容而不是整个页面。
  3. index.html(缩写)

    <html ng-app="app">
    <body>
     <nav class="navbar navbar-default header-navbar" role="navigation">
            <ul class="nav navbar-nav" data-ng-controller="NavController">
                <li class="active"><a href="#">Home</a></li>
                <li ng-repeat="brand in brands">
                    <a href="#/brand/{{ brand.slug }}">{{brand.name}}</a>
                </li>
            </ul>
     </nav>
     <div ng-view></div>
    </body>
    </html>
    

    app.js(缩写)

    var app = angular.module('app',['MockDataService','ngSanitize']).
        config(['$routeProvider',
            function($routeProvider){
                $routeProvider
                    .when('/',
                    {
                        controller: 'SiteController',
                        templateUrl: 'partials/home.html',
                        resolve:{
                            'Brands':function(BrandFactory){
                                return BrandFactory.promise;
                            }
                        }
                    })
    ...
    shop.controller('SiteController',SiteController)
        .controller('NavController',NavController);
    

    控制器

    var SiteController = function ($scope, SiteFactory, BrandFactory){
        $scope.settings = SiteFactory.settings;
        $scope.brands = BrandFactory.getBrands();
        console.log($scope);
    }
    var NavController = function($scope, BrandFactory, $location)
    {
        $scope.brands = BrandFactory.getBrands();
        console.log($scope);
    }
    

    service.js

    var MockDataService = angular.module('MockDataService',[])
        .factory('BrandFactory',function($http){
            var factory = {};
            var brands = {};
            var promise = $http.get('/data/brands.json')
                .success(function(data){
                    brands = data;
                });
    
            factory.getBrands = function(){
                return brands;
            };
            factory.getBrandBySlug = function(slug){
                for(var i=0; i< brands.length; i++)
                {
                    if(brands[i].slug === slug) return brands[i];
                }
            };
    
            factory.promise = promise;
    
            return factory;
        })
    

1 个答案:

答案 0 :(得分:0)

这对我有用:Binding variables from Service/Factory to Controllers

同时观看egghead.io上的视频有助于获得成功(http://www.egghead.io/lessons