Reputation: 41919
this is a jsbin showing the problem, however, I will explain it here. I am trying to use resolve
to run some code before entering a route, however, it doesn't run (as the console.log statement provides more detail about). (Since it doesn't run, I'm not sure if I'm setting what would be the return value from resolve
in the template correctly). Why isn't resolve
running?
var app = angular.module('jsbin', ['ngRoute'])
.config(function ($routeProvider) {
'use strict';
console.log("this runs");
var routeConfig = {
controller: 'DemoCtrll',
resolve: {
store: function (demoStorage) {
console.log("this doesn't log");
return demoStorage;
}
}
};
$routeProvider
.when('/', routeConfig)
.otherwise({
redirectTo: '/'
});
});
app.controller('DemoCtrl', function($scope, $routeParams, store) {
this.name = store;
});
app.factory('demoStorage', function () {
'use strict';
return "World";
});
html
<body ng-app="jsbin">
<div ng-controller="DemoCtrl as demo">
<h1>Hello {{name}}</h1>
</div>
Upvotes: 1
Views: 1008
Reputation: 123739
Some changes you would need:
ng-controller
directive along with ng-view's route bound controller, i.e set controller alias in the controller property of the route config controller: 'DemoCtrl as demo',
. store
provider, because no such provider/service exists. It is a special dependency injected by the angular router and only the router knows how to inject store
as dependency in your controller. That is the reason for the error when you used ng-controller
.templateUrl
property on the routeConfig. i.e templateUrl:'demo.html',
ng-controller
from the view.ng-view
directive to render the view. i.e in your index.html <ng-view></ng-view>
demo.name
in the view rendered by the route.DemoCtrl1
.Overall it will look like this.
Define your template in say Demo.html
(In the demo example i have used the convenient script type="text/ng-template"
)
<div>
<h1>Hello {{demo.name}}</h1>
</div>
Set the routeConfig:
var routeConfig = {
templateUrl:'demo.html',
controller: 'DemoCtrl as demo',
resolve: {
store: function (demoStorage) {
console.log("this doesn't log");
return demoStorage;
}
}
};
Also see this answer though it uses angular ui-router, but the concept is the same.
Upvotes: 2