I'm taking a course on AngularJS on Coursera.
The code that the instructor demonstrated in the videos works but for some reason I couldn't get to run on my environment:
Page Layout (partial):
<div class="media-body">
<h2 class="media-heading">{{dish.name}}
<span class="label label-danger">{{dish.label}}</span>
<span class="badge">{{dish.price | currency}}</span></h2>
<p>{{dish.description}}</p>
</div>
Snippet A (demonstrated by professor that I couldn't get to work):
var app = angular.module('confusionApp',[]);
app.controller('dishDetailController', function() {
var dish={ //attributes here; };
this.dish = dish;
});
When I would run this function, I don't get any errors in the console but I don't get anything in the display.
Snippet B:
var app = angular.module('confusionApp',[]);
app.controller('dishDetailController', function($scope) {
var dish={ //attributes here;};
$scope.dish = dish;
});
When I do it this way, it works. Is there a difference?
Snippet A is not working most likely because of how the controller is being attached. I am taking a wild guess here.
Where you add ng-controller
it should probably look something like:
<body ng-controller="dishDetailController as dish">
Where as you might have this instead:
<body ng-controller="dishDetailController">
Might not be the body tag could be a div or something.
And to make more sense of it inside the snippet A controller try:
var app = angular.module('confusionApp',[]);
app.controller('dishDetailController', function() {
this = {//attributes here}
});
Otherwise you might have to write: {{dish.dish.stuff}}
inside the template.
The second snippet (B) is more or less straight out of the documentation https://docs.angularjs.org/guide/controller and is most likely what you are looking for.
In Snippet A, assigning a value via this
will apply the value directly to the controller itself. This will make it very difficult to access in other contexts, and is most likely not what you want.
Conversely, Snippet B is leveraging the dependency injection provided by AngularJS to ensure that the proper scope is injected into the method. $scope
has a much more complicated lifecycle, but the important thing to note is that this will make dish
available outside the context of your controller, such as in an HTML template.
If you need more details, this guy has a way better answer: 'this' vs $scope in AngularJS controllers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With