Niek Jonkman Niek Jonkman - 6 months ago 18
AngularJS Question

Initializing scope variables in controllers

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?

Answer

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>

http://jsfiddle.net/t0hhp5wz/

Comments