繁体   English   中英

AngularJS-动态DOM操作,无需在控制器中对dom ID进行硬编码

[英]AngularJS - Dynamic DOM manipulation without hardcoding dom id's in the controller

我仍然开始使用angular,似乎“ Angular的事情”是将视图与控制器分开,因此,到目前为止,我在Angular中的DOM操作似乎很笨拙,因为我必须做很多事情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-click将DOM元素发送到控制器? 像ngclick =“ ctrl.animateStuff([#element1],[#element2],[#element3])”之类的东西,所以我的控制器只需要获取参数并操纵它们,甚至不了解DOM? 还是可以为此使用指令? 如果是这样,怎么办?

如果您不能使用Angular的ngAminate(因为它使用css不需要DOM操作),则可以构建一个自定义指令 指令是允许DOM操作的地方,您将把实际的元素传递到指令中,因此不需要硬编码的id。

但我建议遵循@NewDev的建议。

这可能是该指令的存根:

module.directive('myAnimation', function() {
  return {
    restrict: 'A',
    scope: {
      enabled: '='
    },
    link: function(scope, element) {
      // watch on enabled and start animation when set to true
    }
  }
});

和您的标记:

<div my-animation enabled='enabled'></div>
<div my-animation enabled='enabled'></div>
<div my-animation enabled='enabled'></div>
<button ng-click="enabled=true"></button>

要立即解除对您的屏蔽,您可以

<div id="element1" ng-click="ctrl.animateStuff($event)"></div>    

它将事件传递给您的函数,您可以从中提取DOM元素。

我对GSAP并不熟悉,但是您应该能够将其挂接到ngAnimate处理方式中。

而且,我会重复我自己- 不要访问或对控制器中的DOM做任何假设 -您正在破坏Angular的最佳实践,并且经常会发现自己遇到问题和头痛。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM