Reputation: 1056
So I am completely new to AngularJS and followed a course and started "learning" this framework. I watched the 2 screencasts at the top of this page:
https://github.com/curran/screencasts/tree/gh-pages/introToAngular
After watching both screencasts and looking into some of the examples I tried to create my own simple Angular application where I tried to work with some controllers. Now I have the following code:
Index.html
<html ng-app="WIMT">
<head>
<title>trying out angularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript" src="../bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="../JS/app.js"></script>
</head>
<body>
<div ng-controller="controllerA as a">
{{a.varA}}
</div>
<div ng-controller="controllerB as b">
{{b.varB}}
</div>
<div ng-controller="controllerC as c">
{{c.varC}}
</div>
</body>
</html>
JS
(function() {
var app = angular.module('WIMT',[]);
app.controller('controllerA',function($scope,$http){
$scope.varA = "A";
});
app.controller('controllerB',['$scope',function($scope) {
$scope.varB = "B";
}
]);
app.controller('controllerC',function($scope, $http) {
var reg = this;
reg.varC = "C";
});
})();
After I tried to bind varA to the scope in controller A I found out that it didn't work and I looked for a solution on the internet. I have found a few different ways (B & C) that should (could?) work. Only option C works and shows C when I run the html. Both A & B show nothing.
Why do option A and B not work in this example?
Upvotes: 2
Views: 655
Reputation: 528
since you are using controller as
alias, option A & B are placed inside controller scopes which are childScopes of $scope
.
if you console.log
the $scope
you will see option A & B created inside controller scope and not in $scope
which is parent scope for those controllers.
Upvotes: 0
Reputation: 4728
this is pretty the same thing :
app.controller('controllerA',function($scope,$http){
$scope.varA = "A";
});
this syntax will work if you use minification, the previous not.
app.controller('controllerB',['$scope',function($scope) {
$scope.varB = "B";
}
]);
use this syntax in the view :
<div ng-controller="controllerA">
{{varA}}
</div>
Upvotes: 0
Reputation: 23632
Because you are using controllerAs
syntax, that's why the third one is working and first two are not.
<div ng-controller="controllerA as a">
{{a.varA}}
</div>
<div ng-controller="controllerB as b">
{{b.varB}}
</div>
<div ng-controller="controllerC as c">
{{c.varC}}
</div>
If you want the a.varA
and b.varB
to print, you have to change to below:
<div ng-app="app">
<div ng-controller="controllerA as a">
{{varA}}
</div>
<div ng-controller="controllerB as b">
{{varB}}
</div>
<div ng-controller="controllerC as c">
{{c.varC}}
</div>
</div>
Upvotes: 3