目前我有一个有效的应用程序....它可以工作,但我在我的控制器中做一些DOM操作的东西,而不是像我应该的指令。问题是,我的问题变成了,如何使用指令正确实现这种类型的功能?
一个简单的例子是:
<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方法,它给出或看起来像这样:
$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;
}
答案 0 :(得分:0)
你可以创建一个类似于
的指令angular.module('myApp.directives', []).
directive('changeSize', [function() {
return function(scope, elm, attrs) {
function resizeDiv(id, width, height) {
var elem = document.getElementById(id);
elem.style.height = height;
elem.style.width = width;
}
elm.bind("click", function(){
switch (attrs.size) {
case 1:
resizeDiv("container1", "320px" , "240px");
case 2:
resizeDiv("container1", "640px" , "480px");
case 3:
resizeDiv("container1", "1280px" , "960px");
}
});
};
}]);
然后将您的标记更改为:
<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>
答案 1 :(得分:0)
@MDiesel,您的示例演示了指令的用户,但我认为它有一些缺陷。 我相信在执行DOM操作时,或者对于具有API的可重用组件,应该使用指令。
假设用例是纯粹的DOM操作,不会被重用,我会写下以下内容:
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);
}
}
}
}
]);
如果用例是使该指令可重用并且可能包含许多元素,那么它是另一种情况。让我知道,我会写一下这个。