在AngularJS中,jquery each的替代方法是什么?

27

我想从我的应用程序中移除jquery。但我需要在angularjs中找到$ .each的替代品...如何循环遍历dom元素??这是我的代码,我想将其从jquery转换为angularjs。

app.directive('activeu', function($location) {
        return function ($scope, element, attrs) {
            var menuMain = $scope.$parent.menuMain;
            var fullpath = $location.path().split('/');
            var current = fullpath[2];

            setTimeout(function() {
                $(".nav li a").each(function() {
                    if ($(this).attr('href') ==  '#!/page/' + current) {
                        $(this).parent().addClass('active');
                        $(this).closest('li.root-li').addClass('active');

                        if ($(this).closest('li.parent').length > 0) {
                            $(this).closest('li.parent').addClass('active');
                        }
                    }
                });

                $(".nav li a").on('click', function() {
                    current = $(this).attr('href');
                    $("#pages-menu .navigation li").each(function() {
                        if ($(this).hasClass('active')) {
                            $(this).removeClass('active');
                        }
                    });

                    $(".nav li a").each(function() {
                        if ($(this).attr('href') ==  current) {
                            $(this).parent().addClass('active');
                            $(this).closest('li.root-li').addClass('active');

                            if ($(this).closest('li.parent').length > 0) {
                                $(this).closest('li.parent').addClass('active');
                            }
                        }
                    });
                });
            }, 500);
        };
    });
2个回答

67
angular.forEach(angular.element("li a"), function(value, key){
     var a = angular.element(value);
     a.addClass('ss');
});

你可以将其转换为对象,然后使用它。


15

你可以使用循环语句angular.forEach()

var values = {name: 'misko', gender: 'male'};
angular.forEach(values, function(value, key){
  console.log(key + ': ' + value);
});

它给了我这样的变量:var htm = "<a href="#!/login">Login</a>".. 我可以像这样访问它:htm.href.. 但是,如果我想像访问 htm.attr('href') 一样访问它,我该怎么做? - Amb
@amss 我认为你需要分享更多细节,例如你要迭代哪种数据以及期望的输出是什么。 - Arun P Johny
我编辑了我的问题... 我想用angular.forEach替换jquery each。 - Amb
@amss 因为这是一个指令,而且你正在进行 DOM 操作,所以 jQuery 似乎是最合适的选择。 - Arun P Johny
@amss AngularJS 也使用了一个精简版的jQuery库,如果你没有自己引入的话。但是如果你不想使用它,那么你就需要进行原始DOM操作。 - Arun P Johny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接