我试图遵循最佳实践,但在何时使用 $scope 和何时使用 'this' 方面存在困惑。我有一个简单的示例,使用的是 AngularJS 1.4.8。
<!DOCTYPE html>
<html ng-app="testApp">
<head>
<title>Test button action</title>
<script src="./angular.min.js"></script>
<script src="./testBtn.js"></script>
</head>
<body>
<div ng-controller="TestCtrl as test">
<button ng-click="testBtn()">test button</button>
{{testResult}}
</div>
<div ng-controller="Test1Ctrl as test1">
<select ng-model="chosen" ng-change="getDetails(chosen)">
<option value='option1'>Option1</option>
<option value='option2'>Option2</option>
<option value='option3'>Option3</option>
</select>
<p>You choose {{test1Result}}</p>
</div>
</body>
</html>
testBtn.js文件长这样:
(function() {
'use strict';
angular.module("testApp", []);
angular.module("testApp").controller("TestCtrl", testCtrl);
angular.module("testApp").controller("Test1Ctrl", test1Ctrl);
function testCtrl($scope) {
$scope.testBtn = testBtn;
function testBtn() {
if (this.testResult == '' || this.testResult == null) {
this.testResult = "Button clicked";
} else {
this.testResult = '';
}
}
}
function test1Ctrl($scope) {
$scope.getDetails = getDetails;
function getDetails(opt) {
this.test1Result = opt;
}
}
})();
当前代码可以正常运行。但是,如果我将两个函数改为this.testBtn = testBtn;
和this.getDetails = getDetails;
,那么单击按钮或选择选项将无法正常工作,并且控制台日志中不会显示任何错误。
为什么这些示例中的'this'无法正常工作?是否有更好的方法来解决这个问题?