Friday, October 30, 2015

Angular Recipe: Manipulate Dom

Angular JS


Manipulating the DOM from your directive is fairly simple.
You just have to use link function instead of controller into your directive.
Inside directives, it is best practice to use controller only when you want to share functions with other directives. All other times you should use link.

card.js

angular.module('myApp')
.directive('myCard', function() {
    return {
    restrict: 'E',
    templateUrl: './templates/directives/my-card.html',
    scope: {
        header: '=',
        description: '=',
        dealed: '='
    },
    link: function(scope, element) {    
        if (scope.dealed) {
           element.addClass('dealed');
        }
    }  
};
});

Directives should Clean Up after themselves (A clean DOM is a happy DOM)

Best Practice:

 angular.module('myApp')
.directive("title", function() {
return function(scope, element, $timeout) { 
    ...
    scope.$on('$destroy', function() {
        element.tooltip('destroy');
    });
};
});

Destroy method is called whenever the directive is removed (off hover) and its scope is destroyed.

Creating, Using and Destroying attribute Directive:

*.js

angular.module('MyApp')
.directive('popover', function($timeout) {
 return function(scope, element, attr) {
    $timeout(function(){
        element.popover({trigger: 'hover', content: attr.popover});
    });
    // clean up
    scope.$on('$destroy', function() {
        element.popover('destroy');
    });
 };
});

*.html

 <div class="card" popover="{{note.title}} {{note.createdDate | date: 'MMM. dd'}}">
      <h2 class="h3">{{note.title}}</h2>
      <p>{{note.createdDate | date: "'Created on a' EEEE 'in' MMMM"}}</p>
 </div>

see Also


2 comments: