我仍然開始使用angular,並且似乎「事物的角度方式」是將與控制器分開,因此,我角度的DOM操作看起來非常笨重,因爲我必須做大量的手動DOM元素選擇。我的應用程序目前看起來像這樣;AngularJS - 在控制器中沒有硬編碼dom id的動態DOM操作
HTML:
<div ng-controller="appController as appCtrl">
<div>
<div id="element1"></div>
<div id="element2"></div>
<div id="element3"></div>
<button ng-click="appCtrl.animateStuff()"></button>
</div>
</div>
控制器:
app.controller('appController', ['animationFactory', 'domFactory', appControllerFunc]);
function appControllerFunc(animationFactory, domFactory) {
This = this;
This.animateStuff = function() {
animationFactory.animate(domFactory.getNgElementById('element1'));
animationFactory.animate(domFactory.getNgElementById('element2'));
animationFactory.animate(domFactory.getNgElementById('element3'));
}
}
工廠:
app.factory('domFactory', [domFactoryFunc]);
function domFactoryFunc() {
var domFactoryContainer = {
getNgElementById: function(id) {
return angular.element(document.getELementById(id));
}
}
return domFactoryContainer;
}
app.factory('animationFactory');
function animationFactoryFunc() {
var animationFactoryContainer = {
animate: function(ngelement) {
// animates ngelement
}
}
return animationFactoryContainer;
}
有沒有辦法以某種方式從視圖的ng點擊發送DOM元素到控制器?像ngclick =「ctrl.animateStuff([#element1],[#element2],[#element3])」,所以我的控制器只需要獲取參數並操作它們,而不需要知道任何有關DOM的內容?或者可以使用指令嗎?如果是這樣,怎麼樣?
你是對的 - 「對‘的事情角路’是從視圖分離控制器「 - 因此不要對控制器中的DOM做任何假設(如元素ID)。換句話說,如果你覺得你需要從控制器訪問DOM,那麼你做錯了。 – 2014-12-18 23:44:05
在我的問題中添加了更多信息,對不起,它似乎在我寫下來並從記事本複製粘貼時被剪掉 – 2014-12-18 23:48:33
閱讀有關如何在Angular中執行動畫的示例,請參見[ngAnimate](https:// docs。 angularjs.org/api/ngAnimate)。它使用該元素,但它不在控制器中。 – 2014-12-18 23:52:52