I'm trying to follow best practise but have a problem understanding when to use $scope and when to use 'this'. I have a simple example using 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>
The testBtn.js file looks like this
(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 works fine as it stands. However if I change the two functions to say
this.testBtn = testBtn; and this.getDetails = getDetails; clicking the button or choosing an option doesn't work and no errors are shown in the console log.
Why doesn't 'this' work in these examples? Would there have been a better way to do this?