通过指令进行AngularJS DOM操作 [英] AngularJS DOM Manipulation through Directives
问题描述
当前,我有一个工作的角度应用程序....它可以工作,但是我在控制器中而不是像我应该的指令中执行一些DOM操作.问题是,我的问题变成了,如何使用指令正确实现这种类型的功能?
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 question becomes, HOW do i implement this type of functionality properly using directives??
一个简单的例子是:
<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>
从本质上讲,这将调用我的控制器中的changeSize方法,该方法给出或显示如下:
That would essentially call the changeSize method in my controller which give or take looks like this:
$scope.changeVideoSize = function(size) {
switch (size) {
case 1:
resizeDiv("container1", "320px" , "240px");
case 2:
resizeDiv("container1", "640px" , "480px");
case 3:
resizeDiv("container1", "1280px" , "960px");
}
}
function resizeDiv(id, width, height) {
var elem = document.getElementById(id);
elem.style.height = height;
elem.style.width = width;
}
推荐答案
@MDiesel,您的示例演示了指令的用户,但我认为它存在一些缺陷. 我认为在执行DOM操作或具有API的可重用组件时应使用指令.
@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.
假设用例是不会被重用的纯DOM操作,我将编写以下内容:
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) {
case 1:
containerElement.width(320);
containerElement.height(240);
case 2:
containerElement.width(640);
containerElement.height(480);
case 3:
containerElement.width(1280);
containerElement.height(960);
}
}
}
}
]);
- 指令现在是自包含的,您不应该使用文档来更改DOM,它会丢失指令的要点.
- ng-click优于自己监听click事件,它使模板更具解释性.
如果用例是使此指令可重用并且可能包含许多元素,那么这是另一种情况.让我知道,我会写的.
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.
这篇关于通过指令进行AngularJS DOM操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!