为什么实例化的控制器没有显示我的消息?

时间:2013-12-24 21:40:56

标签: angularjs

在我的角度HotorNot games / show.haml代码中,这不起作用:

.game{'ng-controller' => 'GamesCtrl as game'}
  %h1 Hi {{game.player}}, Is this person Hot or Not?

虽然这样做:

.game{'ng-controller' => 'GamesCtrl as game'}
  %h1 Hi {{player}}, Is this person Hot or Not?

这是我的角度应用和控制器:

var myApp = angular.module('HotorNot', ['ngResource']);

myApp.controller('GamesCtrl', ['$scope', function($scope) {
  $scope.player = 'Stephanie';
}]);

为什么变量“游戏”在这里不起作用?我试图遵循我听过的建议,总是使用一个。

根据请求更新,生成html:

<html ng-app="HotorNot" class="ng-scope"><head><style type="text/css">@charset "UTF-8";[ng\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide{display:none !important;}ng\:form{display:block;}</style>
    <title>AngularFun</title>
    <link href="/assets/application.css?body=1" media="all" rel="stylesheet">
    <meta content="authenticity_token" name="csrf-param">
    <meta content="NAKzONXDIcfeoGZxqhSn8mqFvceAQBxIxvf+lso2Ibo=" name="csrf-token">
  </head>
  <body>
    <div class="game ng-scope" ng-controller="GamesCtrl as game">
      <h1 class="ng-binding">Hi Stephanie, Is this person Hot or Not?</h1>
      <div class="voting_image">
        <img alt="Stock footage pretty girl is listen to the music in headphones" src="http://ak1.picdn.net/shutterstock/videos/1321426/preview/stock-footage-pretty-girl-is-listen-to-the-music-in-headphones.jpg">
      </div>
      <button>Hot</button>
      <button>Not</button>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular-resource.js"></script>
    <script src="/assets/app.js?body=1"></script>
    <script src="/assets/angular/controllers/games_ctrl.js?body=1"></script>
    <script src="/assets/application.js?body=1"></script>


</body></html>

1 个答案:

答案 0 :(得分:1)

如果要使用“controller as”语法,则需要在控制器内的this上声明变量。

这是因为GamesCtrl as game构造告诉angular你希望game成为对控制器构造函数实例的引用。

所以,如果你想使用GamesCtrl as game而不是你的控制器需要看起来像:

myApp.controller('GamesCtrl', ['$scope', function($scope) {
  this.player = 'Stephanie';
}]);

否则,如果在player上定义了$scope,那么只能通过直接引用(Hi {{player}} ...)从您的视图中访问$scope,这是因为所有视图表达式都是针对当前{进行评估的{1}}。