简体   繁体   中英

AngularJS route resolve when calling controller using ng-include

Please see my plunkr here

https://plnkr.co/edit/hk7Z0jMwOfoUwJZ98F7a?p=preview

In my app.js I have two controllers and a routeprovider with a resolve for TestController

var app = angular.module('app', ['ngRoute']);


app.controller('DefaultController', ['$scope', function($scope){
  $scope.welcome = "Hello World";  
}]);

app.controller('TestController', ['$scope', 'context', '$routeParams', function($scope, context, $routeParams){
  $scope.text = "TestController loaded!"  
}]);

app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider){
  $routeProvider.
    when('/test1',{
      templateUrl: 'test1.html',
      controller: 'TestController',
      resolve: {
        context: function(){return 'test';}
      }
    })
}])

In my html, I have an ng-include which should also load test.html in the default view

 <body ng-controller="DefaultController">
    <h1>{{welcome}}</h1>

    <div ng-include="'test.html'" ng-controller='TestController'></div>


  </body>

I cannot take the resolve out of the routeProvider as I still need it to when the user goes to '../test'

Is there any way I can resolve contextProvider from the ng-include?

or is there better ways to do this?

Any help would be greatly appreciated.

Create a factory/service and use that:

app.factory('fooResolver', function() {
    return {
        resolveMe: function() {
            return 'test';
        }
    }
});

Now, use this in your router config:

app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider){
  $routeProvider.
    when('/test1',{
      templateUrl: 'test1.html',
      controller: 'TestController',
      resolve: {
        context: function(fooResolver) {
             return fooResolver.resolveMe();
        }
      }
    })
}])

And do the same in your controller:

app.controller('TestController', ['$scope', 'fooResolver', '$routeParams', function($scope, fooResolver, $routeParams){
  $scope.text = "TestController loaded!"
  var context = fooResolver.resolveMe();
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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