在加载'/'时,我得到'内容'和'侧边栏'使用'myService'并解决路由提供程序中的选项,我可以将'内容'呈现给模板($ scope.contents = content;)。
但$ scope.sideBar = sideBar;不管用。这是因为sideBar在模板之外?
如何在加载'/'时呈现侧边栏项?是否可以将此数据(侧边栏)传递给indexCtrl?
app.js
var myApp = angular.module("MyApp", ['ngRoute']);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'contents.html',
controller: 'Myctrl',
resolve: {
content: function(myService){
return myService.getContent();
},
sideBar: function(myService){
return myService.getSideBar();
}
}
}).
otherwise({
redirectTo: '/'
});
}]);
myApp.controller('Myctrl', function (content, sideBar, $scope) {
$scope.contents = content;
$scope.sideBar = sideBar;
});
myApp.controller('indexCtrl', function($scope) {
});
myApp.service("myService", function () {
this.getContent = function () {
return 'Main contents';
}
this.getSideBar = function () {
return 'side bar'
}
});
的index.html
<div ng-app="MyApp" ng-controller="indexCtrl">
<div class="sidebar">
{{sideBar}}
</div>
</div>
<div class="main">
<div ng-view></div>
</div>
</div>
contents.html
<div>{{contents}}</div>
答案 0 :(得分:2)
您可以将myService注入indexCtrl并像这样访问函数getSideBar
myApp.controller('indexCtrl', function($scope, myService) {
$scope.sideBar = myService.getSideBar();
});
首次初始化indexCtrl时,这将从getSideBar函数中获取字符串。如果你这样做:
myApp.controller('indexCtrl', function($scope, myService) {
$scope.sideBar = myService.getSideBar;
});
并在index.html内部:
<div class="sidebar">
{{sideBar()}}
</div>
当服务中的数据更新时,字符串将更新。