Pergunta

I'm working with AngularJS at the moment and in my current Project i've got to append a row from table1(in which a button is clicked by a user) to a 2nd table. On top of this the button also has to perform a $http.post(...).

So what i got is a table with data populated by ng-repeat and in one of the td's i have a button with the ng-click directive which executes a function with a $http.post.

html:

<table id="tableOne">
    <thead>
        <th>ID</th>
        <th>Name</th>
        <th>Age</th>
        <th></th>
    </thead>
    <tbody id="source">
    <tr ng-cloak ng-repeat="person in persons">
        <td>{{ person.id }}</td>
        <td>{{ person.name }}</td>
        <td>{{ person.age }}</td>
        <td><button ng-click="movePerson(person.id)">Move to 2nd Table</button></td>
    </tr>
    </tbody>
</table>

When I click on the Button the function "movePerson(person.id) in my Controller will be called and that works fine.

controller:

$scope.movePerson = function ( id ) {

    DataService.movePerson( id, { result: function ( data, status ) {
        if( data.success === true )
        {
            $log.log( "person has been moved" );
        }
    }, fault: function ( data, status ) {
            $log.log( "an error has occured" );
    } } );
};

'DataService' is handling my $http requests.

Now I want to move the tablerow where the button was clicked to another table(id="tableTwo") with tbody id="target". I've read you shouldn't use jQuery in your Controller.. so is there an "angular-way" to do this? Because i would like to not include jQuery at all in my Project.

I thought you would use a directive for these kind of things, so that you can just add the directive in the button tag like the "ng-click" like this:

<td><button ng-click="movePerson(person.id)" move-tbl-row>Move to 2nd Table</button></td>

But since i'm new to Angular i don't know how my directive would look like. And will the "ng-click" still be executed then?

Geetings and Thanks.

Foi útil?

Solução

You are asking how to move the row ....thinking like jQuery....when in fact you want to change the array the data object is in.

Here's a slight modification for you.

<!-- pass whole object into scope function -->
<button ng-click="movePerson(person)">Move to 2nd Table</button>
$scope.movePerson = function ( person ) {
   var id= person.id;
    /* on ajax success, remove from persons array */
    var idx= $scope.persons.indexOf(person);
    $scope.persons.splice(idx,1);
    /* add person object to another scope array*/
     $scope.another_array.push(person);


})
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top