0

Hey thanks for checking out my question. I am trying to find angular elements by class and push them into an array for another function.

 $scope.find = function () {
    var someVar = [];
    $scope.element.find('.selectedRow').each(function(){
        someVar.push($(this).find('td').eq(0).text())

    })
    return rows;
    console.log(rows);
};
  • 1
    Working with the DOM in a controller is a huge red flag with angular. What exactly are you trying to accomplish? – dnc253 Jul 25 '14 at 17:36
  • I have a table where I can click the rows to select them, I am trying to implement a function to find the rows based on the selection and filter only the selected rows. – user3791317 Jul 25 '14 at 17:40

4 Answers4

1

First off, I highly recommend reading this answer about how to "think" in angular: https://stackoverflow.com/a/15012542/1014979

With angular, you need to think in terms of the model, not the DOM. So, you should add some ng-clicks to your rows that will add them to your array (and probably remove them from the array when deselected). Then you have your array in your model already without need to do any selecting from the DOM.

Community
  • 1
  • 1
dnc253
  • 39,967
  • 41
  • 141
  • 157
0

You can make use of

angular.element(element);

and in your case

angular.element(document.querySelector('.selectedRow'))

where element can be your class selector

V31
  • 7,626
  • 3
  • 26
  • 44
0

I would recommend using(creating) a directive for that.

Fortuna
  • 611
  • 6
  • 18
0

As mentioned by dnc253, referencing the DOM from your controller is not an effective way to develop in Angular. Another way you might do this:

Inject the data in the table into your view from the controller:

.controller('controllerName', ['$scope', function($scope) {
    $scope.rows = [
        { col1: 'foo', col2: 'bar', selected: false },
        { col1: 'baz', col2: 'foo', selected: false }
    ];
}]);

Use the ng-repeat directive to render the models in your view script:

<table>
    <tr ng-repeat="row in rows" ng-click="toggleRow(row)">
         <td>{{ row.col1 }}</td>
         <td>{{ row.col2 }}</td>
    </tr>
</table>

Provide the toggleRow function in your controller to toggle the selected property on your row:

$scope.toggleRow = function (row) {
    row.selected = !row.selected;
}

Now you can track the selected rows from your controller, since each row has the selected property.

Simon Robb
  • 1,668
  • 1
  • 14
  • 25