16.07.2017 Views

AngularJS Essentials

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5<br />

In the previous example, we changed the value of the dialog property directly from<br />

the ngClick directive declaration. The best choice in this case would be to delegate<br />

this intention to the controller and let it control the state of the dialog, such as the<br />

following code in the faq.html file:<br />

Open<br />

<br />

<br />

FAQ<br />

<br />

<br />

You are in the Frequently Asked Questions!<br />

<br />

<br />

Close<br />

<br />

<br />

Consider the following code snippet in the controllers.js file:<br />

parking.controller("faqCtrl", function ($scope) {<br />

$scope.faq = false;<br />

$scope.openFAQ = function () {<br />

$scope.faq = true;<br />

}<br />

$scope.closeFAQ = function () {<br />

$scope.faq = false;<br />

}<br />

});<br />

The idea to spread a variable across the whole view is definitely dangerous. It<br />

contributes to reducing the flexibility of the code and also increases the coupling<br />

between the view and the controller.<br />

Avoid reading the scope inside the controller<br />

Reading the $scope object inside the controller instead of passing data through<br />

parameters should be avoided. This increases the couple between them and makes the<br />

controller much harder to test. In the following code snippet of the login.html file, we<br />

will call the login function and access its parameters directly from the $scope object:<br />

<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!