我正在尝试遵循最佳实践,但无法理解何时使用 $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”在这些示例中不起作用?是否有更好的方法来做到这一点?
最佳答案
当你使用 ng-click="testBtn()"
时,angular 默认会在 $scope
中寻找 testBtn
函数 Controller 的对象。因此,如果您没有将上述函数定义为 $scope.testbtn = function()...
,angular 将不会执行任何操作,因为函数未定义。
在 Controller 的as
语法中,函数/模型是使用 Controller 的this
范围定义的。使用 this
的最佳做法是将其存储在变量中 Controller 的第一行,这样您就不会陷入任何范围冲突。
angular.module("testApp").controller("Test1Ctrl", test1Ctrl);
function testCtrl($scope) {
var ctrlScope = this;
ctrlScope.testBtn = function() {
if (ctrlScope.testResult == '' || ctrlScope.testResult == null) {
ctrlScope.testResult = "Button clicked";
} else {
ctrlScope.testResult = '';
}
}
}
<div ng-controller="TestCtrl as test">
<button ng-click="test.testBtn()">test button</button>
{{test.testResult}}
</div>
在我看来,“as”语法使代码更具可读性,并且如果嵌套了 Controller ,还可以处理名称冲突。
关于javascript - Angularjs 最佳实践 - $scope 与 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35128709/