按摩与AngularJS的DOMAngularJS、DOM

2023-09-13 03:17:52 作者:命运の我手中

我知道操纵DOM违背了角的规则,但在这种情况下,我有做横向的DOM修改同级节点。

I know manipulating the DOM goes against the rules of Angular but in this case, am having do transverse the DOM to modify a sibling node.

在jQuery的你可以做这样的事情:

In jQuery you can do something like this:

$(本).parent()addClass('装'); 的

$(this).parent().addClass('.loading');

虽然角,你会做这样的事情:

While in Angular you would do something like this:

angular.element(本).parent()addClass('装'); 的

angular.element(this).parent().addClass('.loading');

当然,这并不工作,因为没有对API父()方法或addClass()方法的支持。

Certainly this doesn't work because there is no parent() method or addClass() method support on the API.

这使我的问题,我还能怎么做到这一点?

Which brings me to the question, how else can I accomplish this?

谢谢!

推荐答案

角元素包裹着的 jqLit​​e 默认(角自己的jQuery的实现)。如果您已经添加的jQuery到您的项目,那么元素包裹着全jQuery的。

Angular elements are wrapped with jqLite by default (Angular's own jQuery implementation). If you have added jQuery to your project, then elements are wrapped with full jQuery.

下面是可使用jQuery精简版http://docs.angularjs.org/api/angular.element

Here's a list of methods available with jQuery lite http://docs.angularjs.org/api/angular.element

正如你所看到的,你有机会获得父() addClass()所以,你得到了很多W / O添加的jQuery作为依赖DOM操作的动力。

As you can see, you have access to parent() and addClass() So you get a lot of DOM manipulation power w/o adding jQuery as a dependency.

- * -

-*-

这是完全罚款的角度来操纵DOM,最好的做法是从指令去做,这里是有机会获得父元素的元素的小例子

It's perfectly fine to manipulate the DOM with angular, the best practice is to do it from directives, here's a little example of an element having access to the parent element

HTML

<div ng-app='app'>
    <div id="someparent">
        <div my-directive>
        </div>
    </div>
</div>

在您的JS

var app = angular.module('app', []);


app.directive('myDirective', function(){
    return{
        restrict: 'A',
        link: function(scope, element, attributes){
            console.log(element.parent().attr('id'));  // "someparent"
            element.parent().addClass('loading');    // adding loading class to parent
        }
    };
});​​​​​​​​​​​​​

的jsfiddle: http://jsfiddle.net/jaimem/Efyv4/1/

当然,构建应用程序时,你可能希望有内部指令操作本身仅元素。

Of course when building your app you might want to have directives manipulating only elements within itself.

- * -

-*-

此外,马克提到,您可以使用角度现有的指令,如 ngClass ,而不是创建自己的。目前尚不清楚你想要达到什么样的,但是我建议在看 ngCloak 。

Also, as Mark mentions, you can use angular's existing directives such as ngClass instead of creating your own. It's not clear what you want to achieve, but I recommend looking at ngCloak.