我知道有类似的问题已被提出,我已经阅读了答案,但我仍然没有得到这个,所以任何帮助都将不胜感激。
以下代码有效。但是,如果我在$scope
和this
函数(第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现在提供了相同的功能,这很棒!
答案 0 :(得分:1)
您使用controller as
语法。这意味着可以使用this
访问添加到tester.
的所有内容,添加到$scope
的所有内容都可以(仅限)使用 test.
。
现在应该清楚为什么this.offOrOn
不起作用:在您的HTML中,您不能使用tester.offOrOn
。