2015-11-02 33 views
2

我有一個很奇怪的問題,它顯然似乎簡單的視圖模板阻止控制器被執行,我不明白爲什麼。 我已經建立了一個簡單的plunker 代碼是在這裏:當有一個視圖部分時,UI路由器沒有運行控制器

angular.module('plunker', ["ui.router"]) 
    .config(function($stateProvider, $urlRouterProvider, $locationProvider) { 
    $urlRouterProvider.otherwise("/nested"); 
    $stateProvider 
     .state('nested', { 
     url: '/nested', 
     controller: function($scope) { 
      $scope.sayHi = 'Hi'; 
      this.sayHello = 'Hello'; 
     }, 
     controllerAs: 'dog', 
     //If I comment the "views" section, controller runs correctly 
     views: { 
      'main': { 
      template: 'MainContent' 
      }, 
      'secondary': { 
      template: 'SecondaryContent' 
      } 
     } 
     }) 
    $locationProvider.html5Mode(false).hashPrefix('!'); 
    }) 

HTML:

<div ui-view> 
    <h1>{{dog.sayHello}}</h1> 
    <h1>{{sayHi}}</h1> 
    <p>Why no "hello" or "Hi" over here?</p> 
    <div ui-view="main"></div> 
    <div ui-view="secondary"></div> 
</div> 

如果我在狀態定義中的「意見」部分註釋掉,控制器正常運行。

[編輯] 感謝拉迪姆,我下定決心朝着意見部分控制器定義:

      views:{ 
          '':{ 
           controller: function ($scope) { 
            this.page = 'ten'; 
           }, 
           controllerAs:'dog' 
          }, 
          '[email protected]':{ 
           template:'MainContent' 
          }, 
          '[email protected]':{ 
           template:'SecondaryContent' 
          } 
         } 

回答

1

檢查:

controller總是屬於查看,而不是狀態

an updated plunker

.state('nested', { 
    url: '/nested', 
    //controller: function($scope) { 
    // $scope.sayHi = 'Hi'; 
    // this.sayHello = 'Hello'; 
    //}, 
    //controllerAs: 'dog', 
    //If I comment the "views" section, controller runs correctly 
    views: { 
     'main': { 
     //template: 'MainContent', - let's use view, to consume dog.sayHello 
     templateUrl: 'view2.html', 
     controller: function($scope) { 
      $scope.sayHi = 'Hi'; 
      this.sayHello = 'Hello'; 
     }, 
     controllerAs: 'dog', 
     }, 
     'secondary': { 
     template: 'SecondaryContent', 
     controller: ... 
     } 
    } 

檢查the updated plunekr

+0

好。很高興看到我的解決方案爲您工作。你可以接受的答案 –

+0

對不起,目前我沒有看到任何接受按鈕,如果我看到它,我會點擊它肯定 –

+0

如果你不介意,我建議通過這個非常短的和非常翔實的旅遊http://stackoverflow.com/tour ...知道它是如何工作的真的很好。如果你有一些業餘時間,這也是不錯的閱讀:http://stackoverflow.com/help。祝你好運,先生;)享受SO –

相關問題