角度

时间:2015-10-25 06:26:12

标签: javascript angularjs angularjs-directive angularjs-scope

我知道有类似的问题已被提出,我已经阅读了答案,但我仍然没有得到这个,所以任何帮助都将不胜感激。

以下代码有效。但是,如果我在$scopethis函数(第3行和第6行)之前使用bindTest而不是clickTest,则它不起作用。谁能告诉我为什么?从我读过的内容来看,我希望$scope可以在这里工作。

另一方面,如果我在this之前使用$scope代替offOrOn(第8行),那么就可以了。

angular.module('myTestApp', [])
        .controller('MyTestController', function($scope) {
          this.bindTest = function() {
            console.log("bindTest");
          }; 
          this.clickTest = function() {
            console.log("clickTest");
            $scope.offOrOn = 'on';
          };       
        });
button {
 height:25px;
 width:25px; 
}
.on {
 background-color:red;
}
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myTestApp" ng-controller="MyTestController as tester">
 <p ng-bind="tester.bindTest()"></p>
 <button ng-class="offOrOn" ng-click="tester.clickTest()"></button>
</div>
</body>

另外,我试图创建a fiddle,但它不起作用,Chrome开发者控制台告诉我它不会加载模块。我很好奇那里有什么问题。但是,stackoverflow现在提供了相同的功能,这很棒!

1 个答案:

答案 0 :(得分:1)

您使用controller as语法。这意味着可以使用this访问添加到tester.的所有内容,添加到$scope的所有内容都可以(仅限)使用 test.

现在应该清楚为什么this.offOrOn不起作用:在您的HTML中,您不能使用tester.offOrOn