In angular, the data in the controller can be accessed using the $ scope keyword or aliased to the controller and then accessed via $ this. What is the difference ?
Closed due to the fact that the essence of the issue is incomprehensible to the participants Grundy , Ivan Pshenitsyn , αλεχολυτ , user194374, aleksandr barakin 19 Aug '16 at 7:07 .
Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .
|
1 answer
When using the "controller as" syntax, an object is created in $ scope in which all controller methods are stored. This makes it possible to use these methods in any of the child $ scope, for example, in a nested controller:
var ControllerOne = function($scope) { var _this = this; _this.$scope = $scope; _this.$scope.name = 'Vladimir'; }; ControllerOne.prototype = { alert: function() { var _this = this; alert('Hello ' + _this.$scope.name); } }; var ControllerTwo = function($scope) { var _this = this; _this.$scope = $scope; }; angular.module('test', []) .controller('controllerOne', ['$scope', ControllerOne]) .controller('controllerTwo', ['$scope', ControllerTwo]); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="test" ng-controller="controllerOne as ctrl"> <div ng-controller="controllerTwo as parentCtrl"> <button ng-click="ctrl.alert()">Alert</button> </div> </div> - rather , an object is not created in which all the methods of the controller are stored , but the created instance of the controller is saved - Grundy
- Well, in your example there is no appeal through $ this - Grundy
- What's the point of storing this inside the alert function? it is right there and is used immediately, not to mention the fact that there is no point in looping objects, saving the
$scopein which the link to the controller is stored to this controller. Even more than that,$scopein this case is not needed at all - Grundy - String var _this = this; Gives us access to the stored _this in the controller function, since we hang the method on the prototype, the _this variable is not available to us through the closure. - D.Nazarenko
- I did not understand anything, where is the closure, but if I remove this assignment here, nothing will change, and nothing will change anything, if $ Scope is also removed — Grundy
|
$this? Where does this appeal take place? - Grundy