I'm trying to grasp the concept of using named controllers with the controller as syntax in Angular. Within my application, I have assigned the same controller to different divs, always naming the controller as myCtrl as C
in the HTML. Inside the controller, I make use of this
to refer to its properties and methods. The controller contains variables and methods that are linked to and called from the HTML page.
I've encountered some unusual behavior that I attempted to replicate in the following example:
var app = angular.module("myApp", []);
app.controller("ctrl1", function(){
var vm = this;
vm.name = "Pippo";
vm.msg = function(){alert(vm.name)}
})
app.controller("ctrl2", function(){
this.name = "Pippo";
this.msg = function(){alert(this.name)}
})
app.controller("ctrl3", function($scope){
$scope.name = "Pippo";
$scope.msg = function(){alert($scope.name)}
});
http://jsfiddle.net/k66Za/111/
In my specific scenario, I am using ctrl1
. Upon clicking the first button, I expect it to return the name associated with ctrl1, however, it returns the name associated with ctrl2 instead.
I acknowledge that this discrepancy is due to my lack of understanding, but I am unable to discern the difference between ctrl1 and ctrl2.
Could someone please clarify what's going on in my example and advise on whether I should use $scope
, this
, and why there is a distinction between using vm
(where vm = this
) versus using this
?