AngularJS ng-repeat jQuery find returns only one element

泪湿孤枕 提交于 2020-01-03 05:37:27

问题


I am developing my first AngularJS app, and came across this problem with jQuery find function. Basically what I am trying to do, is that I have an custom HTML component . It contains list of buttons using ng-repeat directive. Each has it's own ng-click listener, and in it's callback I want to find all app-item elements, but sadly it only returns me the first one.

I think this is the case I should use link, but I cannot come with it myself.

Part of app-screen.html:

<div>    
    <div ng-repeat="error in _errorData.errors">
        <button class="app-item" ng-click="_onApplicationContainerClick($event)">
            <div class="col-xs-4">
                {{error.date}}
            </div>
            <div class="col-xs-4">
                {{error.errorID}}
            </div>
            <div class="col-xs-3">
                {{error.message}}
            </div>
            <div class="col-xs-1">
                <span class="glyphicon glyphicon-collapse-down"></span>
            </div>
        </button>
    </div>
</div>

AppScreen directive:

angular.module('ErrorViewer').directive('appScreen', function () {
    return {
        restrict: 'E',
        templateUrl: 'src/view/scene/app-screen.html',
        controller: 'AppScreenController'
    };
});

Part of AppScreenController:

$scope._onApplicationContainerClick = function (e) {
    // some executions
    _collapseErrorData();
};

var _collapseErrorData = function () {
    var elems = $element.find( '.app-item' );
    // Should return array of ng-repeated elements!
}

回答1:


ng-repeat is rendered during the render phase (when the $watch handlers are being executed). During the compile and link phases, you only have access to the template. That is the reason you're only seeing one element.

To hook into the after-render phase, you can use $timeout:

app.controller('AppScreenController', function($scope, $timeout) {
     var _collapseErrorData = function () {
        $timeout(function() {
            var elems = $element.find( '.app-item' );
            // Should return array of ng-repeated elements!
        });
     }
});


来源:https://stackoverflow.com/questions/24821208/angularjs-ng-repeat-jquery-find-returns-only-one-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!