如何通过Web服务响应内容构建导航菜单?

时间:2015-09-21 11:01:31

标签: javascript html angularjs web-services

我的目标是检索导航菜单栏和要从后端REST网络服务显示的内容。

我怎样才能实现它?我有以下代码,但到目前为止无效:

testpage.html:

<div ng-controller="testController>
    <li ng-repeat="nav in navs">
        <a href="{{nav.link}}">{{nav.name}}</a>
    </li>
</div>
<!-- content... -->
<script src="js/main.js"></script>
<script src="js/navigationService.js"></script>
<script src="js/testController.js"></script>

main.js:

app.config(function($routeProvider, $locationProvider) {
    $routeProvider.when("/test", {
        templateUrl : "templates/testpage.html",
        controller : "testController"
    }).otherwise({
        templateUrl : "templates/error.html"
    });
});

navigationService.js:

angular.module("test").service('navigationService', function(data) {
    this.initNavigation = function(data) { //assume a json object with fields is passed
        //process the data and apply some modifications, then set the scope variable to init the menu
        $scope.navs = data; 
    }
});

testController.js:

angular.module("test").conroller('testController', ['$scope', '$http', 'navigationService', function($scope, $http) {
    $http.get(url)
        .success(function(data) {
            navigationService.initNavigation(data.navs); //creates navigation from json
            //process the content
    });
}]);

问题:

  • 如何正确初始化navigationService?我后来想在多个控制器中使用此服务。 我应该将服务放在main.js中,还是应该将它留在单个文件中?
  • testpage.html检索并初始化json时,如何在navigationService中触发菜单生成?

0 个答案:

没有答案