Reputation: 1190
I have ui router state like this:
$stateProvider.state('parent', {
templateUrl: 'tpl/a.html',
resolve: {
resA: function() {
return { 'value': 'A' };
}
},
controller: function($scope, resA) {
$scope.resA = resA.value;
}
});
In the template html I use another controller (child controller). This child controller need resolve dependency from ui router state. But, it is not injected to child controller.
tpl/a.html
<h1>Hello</h1>
<div ng-controller="ChildCtrl">
</div>
ChildCtrl
var app = angular.module('app', []);
app.controller('ChildCtrl', function($scope, resA) {
// some codes
});
I got an error, that resA unkonwn in ChildCtrl. How to inject resA in ChildCtrl?
Upvotes: 1
Views: 1859
Reputation: 1417
I see 3 options:
1) put the value in $scope of parent controller
//it would be available in child controller in `$scope.a`
$stateProvider.state('parent', {
templateUrl: 'tpl/a.html',
resolve: {
resA: function() {
return { 'value': 'A' };
}
},
controller: function($scope, resA) {
$scope.resA = resA.value;
}
})
.state('parent.child', {
templateUrl: 'tpl/child.html',
controller: function($scope) {
console.log($scope.resA) //'{value: "A"}'
}
});
2) put child controller as controller for a sub-route, and resolve resA there as well
var a = { 'value': 'A' };
$stateProvider.state('parent', {
templateUrl: 'tpl/a.html',
resolve: {
resA: function() {
return a;
}
},
controller: function($scope, resA) {
$scope.resA = resA.value;
}
})
.state('parent.child', {
templateUrl: 'tpl/child.html',
resolve: {
resA: function() {
return a;
}
},
controller: function($scope, resA) {
$scope.resA = resA.value;
}
});
3) make some service that will provide the data (that now is stored in resA) for controller and inject it to both controllers
Upvotes: 2
Reputation: 971
Checkout @BotanMan's answer.
Also another way, which is similar to the 3. answer.
Put your resource into a service.
var app = angular.module('app');
app.service('resA', function() {
// your service here
});
And include it like so :
$stateProvider.state('parent', {
templateUrl: 'tpl/a.html',
resolve: {
resA: 'resA' //your service name
},
controller: function($scope, resA) {
$scope.resA = resA.value;
}
});
So you can use that resource, like you intended :
var app = angular.module('app', []);
app.controller('ChildCtrl', function($scope, resA) { //now it should work
// some codes
});
See the docs on resolve.
Upvotes: 0