Angularjs Dom Manipulation Through Directives
Currently I have a working angular app .... It works but im doing some DOM manipulation stuff in my controller rather than in a directive like i should. The problem is and my quest
Solution 1:
You could create a directive that looks something like
angular.module('myApp.directives', []).
directive('changeSize', [function() {
returnfunction(scope, elm, attrs) {
functionresizeDiv(id, width, height) {
var elem = document.getElementById(id);
elem.style.height = height;
elem.style.width = width;
}
elm.bind("click", function(){
switch (attrs.size) {
case1:
resizeDiv("container1", "320px" , "240px");
case2:
resizeDiv("container1", "640px" , "480px");
case3:
resizeDiv("container1", "1280px" , "960px");
}
});
};
}]);
and then change your markup to this:
<div id="container1"></div>
<button type="button" change-size size="1">Small</button>
<button type="button" change-size size="2">Medium</button>
<button type="button" change-size size="3">Large</button>
Solution 2:
@MDiesel, your example demonstrate the user of a directive, but I think it has some flaws. I believe a directive should be used when doing DOM manipulation, or for a reusable component that has an API.
Assuming the use case is pure DOM manipulation that will not be reused, I'd write the following:
angular.module('myApp.directives', []).
directive('resizeable', [function() {
return {
// Might be better to use a URL instead for better readability\maintainability.template: '<div id="container1"></div>' +
'<button type="button" ng-click="changeSize(1)">Small</button>' +
'<button type="button" ng-click="changeSize(2)">Medium</button>' +
'<button type="button" ng-click="changeSize(3)">Large</button>',
link: function(scope, element) {
scope.changeSize = function (size) {
var containerElement = element.find('#container1');
switch (size) {
case1:
containerElement.width(320);
containerElement.height(240);
case2:
containerElement.width(640);
containerElement.height(480);
case3:
containerElement.width(1280);
containerElement.height(960);
}
}
}
}
]);
- Directive is now self contained, you shouldn't use document to change the DOM, it misses the point of a directive.
- ng-click is better than listening to click event yourself, it makes the template more self explanatory.
If the use case is to make this directive reusable and might contain many elements, then it's another case. Let me know and I'll write about that one.
Post a Comment for "Angularjs Dom Manipulation Through Directives"