Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to trigger jQuery DOM Manipulation from within a controller?

So I keep reading that jQuery manipulation from within a Controller is bad practice, but I'm not clear on why, or how to correct.

Below is code from a Youtube tutorial which even the video creator comments is a bad idea, but doesn't explain why and continues to use the bad behavior anyway.

From https://www.youtube.com/watch?v=ilCH2Euobz0#t=553s :

$scope.delete = function() {
    var id = this.todo.Id;
    Todo.delete({id: id}, function() {
        $('todo_' + id).fadeOut();
    });
};

SOLUTION:

Based on Langdon's answer below, I've arrived at the following working code for my own work, which derives slightly from the example code above:

var ProjectListCtrl = function ($scope, Project) {
    $scope.projects = Project.query();
    $scope.delete = function() {
        var thisElem = this;
        var thisProject = thisElem.project;
        var id = thisProject.id;
        Project.delete({id: id}, function() {
            var idx = $scope.projects.indexOf(thisProject);
            if (idx !== -1) {
                thisElem.destroy('removeItem('+idx+')');
            }
        });
    }

    $scope.removeItem = function(idx) {
        $scope.projects.splice(idx, 1);
    }

}

app.directive('fadeOnDestroy', function() {
    return function(scope, elem) {
        scope.destroy = function(funcComplete) {
            elem.fadeOut({
                complete: function() {
                    scope.$apply(funcComplete)
                }
            });
        }
    }
});

This differs from Langdon's answer in a few ways. I wanted to avoid adding a parameter to the ngClick callback, so I'm storing it in thisProject. Also, the example and my code needs to call destroy from within a $http success callback so instead of this which is no longer relevant, I'm storing the clicked element in thisElem.

UPDATE 2:

Updated my solution further to reflect that funcComplete was not actually modifying the original $scope.

like image 485
DanH Avatar asked Apr 01 '13 13:04

DanH


1 Answers

The Angular way to handle this is through a directive. I found a perfect example to cover what you're asking below, although it's not as clean as I'd like. The idea is that you create a directive to be used as an HTML attribute. When the element gets bound to the scope of your controller, the link function is fired. The function fades the element in (totally optional) and exposes a destroy method for your controller to call later.

Update: Modified based on comments to actually affect the scope. Not thrilled with the solution, and it's even jankier because the original author called complete.apply(scope) in his destroy callback, but doesn't use this inside the callback function.

Update 2: Since the directive is the one making the callback asynchronous, it's probably a better idea to use scope.$apply there, but keep in mind that that might get weird if you ever use isolated scope in your directive.

http://jsfiddle.net/langdonx/K4Kx8/114/

HTML:

<div ng-controller="MyCtrl">
  <ul>
      <li ng-repeat="item in items" fadey="500">
          {{item}}
          <a ng-click="clearItem(item)">X</a>
      </li>
  </ul>
  <hr />
  <button ng-click="items.push(items.length)">Add Item</button>    
</div>

JavaScript:

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.items = [0, 1, 2];

    $scope.clearItem = function(item) {
        var idx = $scope.items.indexOf(item);
        if (idx !== -1) {
            //injected into repeater scope by fadey directive
            this.destroy(function() {
                $scope.items.splice(idx, 1);
            });
        }
    };
}

myApp.directive('fadey', function() {
    return {
        restrict: 'A', // restricts the use of the directive (use it as an attribute)
        link: function(scope, elm, attrs) { // fires when the element is created and is linked to the scope of the parent controller
            var duration = parseInt(attrs.fadey);
            if (isNaN(duration)) {
                duration = 500;
            }
            elm = jQuery(elm);
            elm.hide();
            elm.fadeIn(duration)

            scope.destroy = function(complete) {
                elm.fadeOut(duration, function() {
                    scope.$apply(function() {
                        complete.$apply(scope);
                    });
                });
            };
        }
    };
});

As for why, I think it's simply for separation of concerns and perhaps usability. Your controller should be concerned with data flow and business logic, not interface manipulation. You directives should ideally be written for usability (as in the case of fadey here -- ed. note: I wouldn't call it fadey ;)).

like image 76
Langdon Avatar answered Nov 03 '22 02:11

Langdon