2016-02-18 27 views
0

在加载'/',我得到'内容'和'侧栏'使用'myService'和解决选项的路线提供商,我可以'模板'内容' scope.contents = content;)。angularjs:获取路线解析数据以外的模板

但是$ 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

在$ scope变量的地方使用$ rootscope或者你可以直接在你的控制器中注入你的服务 –

+0

嘿,grandcoder如果它有帮助,请将我的答案标记为正确。干杯;) –

+1

谢谢@AshkanAldini – grandcoder

回答

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> 

字符串将更新时,在您的服务更新的数据。