In my main webpage, there are just two sections: a navigation bar and the changing content.
index.html:
<div ng-controller='MainCtrl'>
<li ng-repeat="nav in navs">
<a href="#{{nav.url}}">{{nav.name}}</a>
</li>
</div>
<div ng-view></div> <!-- replaced by ngRoute -->
The navigation is set up in the following way:
app.config(function($routeProvider, $locationProvider) {
$routeProvider.when("/test", {
templateUrl : "templates/test.html",
controller : "testController"
});
});
The headlines for the links should be fetched from the backend with each webservice request.
Question: How can I call the init
function from another controller (the one that receives the get response)? Later on, I want to call this method from various controllers.
app.controller('MainCtrl', ['$scope', function($scope) {
this.init = function(data) {
$scope.navs = data;
}
}]);
I attempted the following method, but it did not work:
test.html:
<div>
<h1>content provided by testController.js</h1>
</div>
testController.js:
angular.module('test').controller('testController', ['$scope', '$http', '$controller', function($scope, $http, $controller) {
$http.get(url)
.success(function(data) {
$controller('MainCtrl').init(data.mynavigation); //assuming navigation exists
//process content in data
});
}]);
Result:
Error: [$injector:unpr] http://errors.angularjs.org/1.4.3/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20MainCtrl