2016-02-18 30 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> 

字符串將更新時,在您的服務更新的數據。