2015-11-02 31 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 –

相关问题