gpt4 book ai didi

javascript - angularjs:在模板之外获取路由解析数据

转载 作者:行者123 更新时间:2023-12-02 15:00:13 25 4
gpt4 key购买 nike

加载“/”时,我使用“myService”获取“内容”和“侧边栏”,并在路由提供程序中解析选项,并且可以将“内容”渲染到模板($scope.contents = content;)。

But $scope.sideBar = sideBar; is not working. This is because sideBar is outside the template ?

How can I render sidebar items on loading '/' ? Is it possible to pass this data (sidebar) to the 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>

内容.html

<div>{{contents}}</div>

最佳答案

您可以将 myService 注入(inject)到 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>

当您的服务中的数据更新时,该字符串将会更新。

关于javascript - angularjs:在模板之外获取路由解析数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35480753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com