Javascript angularjs:获取模板外的路由解析数据
加载“/”时,我使用路由提供程序中的“myService”和“resolve”选项获取“content”和“sidebar”,我可以将“content”呈现到模板($scope.contents=content;) 但是$scope.sideBar=侧边栏;它不起作用。这是因为侧边栏在模板之外 如何在加载“/”时呈现侧边栏项?是否可以将此数据(侧栏)传递到indexCtrl app.jsJavascript angularjs:获取模板外的路由解析数据,javascript,angularjs,angularjs-routing,Javascript,Angularjs,Angularjs Routing,加载“/”时,我使用路由提供程序中的“myService”和“resolve”选项获取“content”和“sidebar”,我可以将“content”呈现到模板($scope.contents=content;) 但是$scope.sideBar=侧边栏;它不起作用。这是因为侧边栏在模板之外 如何在加载“/”时呈现侧边栏项?是否可以将此数据(侧栏)传递到indexCtrl app.js var myApp = angular.module("MyApp", ['ngRoute']); myA
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>
{{sideBar}}
contents.html
<div>{{contents}}</div>
{{contents}
您可以将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;
});
和inside.html:
<div class="sidebar">
{{sideBar()}}
</div>
{{sideBar()}}
当服务中的数据更新时,字符串将更新。您可以将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;
});
和inside.html:
<div class="sidebar">
{{sideBar()}}
</div>
{{sideBar()}}
当服务中的数据更新时,字符串将更新。在$scope变量处使用$rootscope,或者您可以直接将服务注入控制器Hey grandcoder请将我的答案标记为正确(如果有帮助)。干杯;)感谢@AshkanAldiniUse$rootscope在$scope变量的位置,或者您可以直接将您的服务注入控制器Hey grandcoder请将我的答案标记为正确(如果有帮助)。干杯;)谢谢@AshkanAldini