Dmitry Dmitry - 5 months ago 9
AngularJS Question

Strange AngularJS beginner behavior

I am starting learning AngularJS but I've stumbled across a strange behavior I can't quite understand where the (() => {}) notation is not equivalent to (function(){}).

My index.html:

<!DOCTYPE html>
<html ng-app="gemStore">
<head>
<title>AngularJS Store</title>
<script src="./angular.min.js"></script>
<script src="./app.js"></script>
</head>
<body>
<div ng-controller="StoreController as store">
<h1>{{store.product.name}}</h1>
<h2>${{store.product.price}}</h2>
<p>{{store.product.description}}</p>
</div>
</body>
</html>


My app.js (closure stripped for debugging).

var app = angular.module('gemStore', []);

app.controller("StoreController", function() {
this.product = gem;
});

var gem = {
name: 'Dodecahedron',
price: 2.95,
description: '. . .'
};


In app.js, if I change

app.controller("StoreController", function() {
this.product = gem;
});


to

app.controller("StoreController", () => {
this.product = gem;
});


My page no longer displays the gem information(just blanks and the dollar sign remain).

Can somebody explain why this happens?

AngularJS version: v1.5.6

Opera version: 37.0.2178.54

Answer

You shouldn't use arrow functions if you need this context.

Read more here(13.2): http://exploringjs.com/es6/ch_arrow-functions.html

Comments