What are the advantages/disadvantages to a declarative template? ViewModel approach?

1.7k Views Asked by At

When talking about a declarative syntax in angularjs we usually always bring up directives, and how we can pass $scope properties down into these directives for processing, DOM manipulation, data gathering and maybe a various combination of those.

Currently, however I'm struggling to convince my team (let alone myself) that a declarative template is the right approach. That doesn't necessarily mean using directives, but how to use the directives.

The following controller/template pair shows an example where I display an element based on the "model"/$scope's properties.

function MainController($scope) {
    $scope.hasJQuery = true;

    $scope.hasProblems = true;

    $scope.hasLodash = false;

    $scope.hasStuff = true;
}

<div ng-controller="MainController">
    <span ng-if="hasJquery && hasProblems && hasLodash && hasStuff">TL;DR?</span>
<div>

But the other approach may look like this

function MainController2($scope) {
    // Get/Retrieve $scope stuff...

    // Setup "ViewModel" Data
    $scope.hasJQueryAndProblemsAndLodashAndStuff = $scope.hasJQuery && $scope.hasProblems && $scope.hasLodash && $scope.hasStuff;

    $scope.hasJQueryAndLodash = $scope.hasJQuery && $scope.hasLodash;
}

<div ng-controller="MainController">
    <span ng-if="hasJQueryAndProblemsAndLodashAndStuff">...</span>
    <span ng-class="hasJqueryAndLodash ? 'blue' : ''"></span>
</div>

The name is an exaggerated version of what could possibly be such as isReady or hasAll but the point was to show that sometimes the html would require multiple ng-class attributes where various logic would rely on $scope properties.

I mostly see the first example being what people usually go with - except in cases where the logic gets really complex. Plus I also know that angularjs is a MVW but that really doesn't help me out.

Should I only add "ViewModel" (presentation logic) to $scope in the controller sometimes? All the time? Never? And what the advantages/disadvantages of putting presentation logic into the controller/template?

0

There are 0 best solutions below