Can we add "id" and "data-id" in the same element dynamically?

时间:2016-04-04 16:46:17

标签: angularjs html5

I need to know if we can use "id" and "data-id" in the same element?

here is my code: this one works fine!

<button class="btn btn-round btn-default" data-id="1" id="1" ng-click='getMyId($event)'>Requete1</button>
<button class="btn btn-round btn-default" data-id="2" id="2" ng-click='getMyId($event)'>Requete2</button>
<button class="btn btn-round btn-default" data-id="3" id="3" ng-click='getMyId($event)'>Requete3</button>

but when i changed it like this :

<tr ng-repeat="pers in queries">
    <td>{{pers.id}}</td>
    <td>{{pers.name}}</td>
    <td>{{pers.description}}</td>
    <h1>XXXX</h1>
    <td>
        <div >
            <button class="btn btn-round btn-default" data-id={{pers.id}} id={{pers.id}}
                    ng-click='getMyId($event)'>{{pers.name}}
            </button>
        </div>
    </td>
</tr>

it doesn't work! It takes only the id or the data-id Or i need to use both of the because i need to get the parentNode ID and this will be with "id" and i need to get theid of thebutton and this is will be done with "data-id"

here is my controller code:

$scope.rep={};
var ids=[];

$scope.rep={};
var ids=[];

$scope.getMyId = function(e){
    //console.log(e.target.parentNode.id);
    var id_q = $(e.target).data('id');
    var id = document.getElementById(id_q).parentNode.id;
    console.log("id_q= "+id_q);
    console.log("id= "+id);
    ids=[id_q,id];
    queryProvider.getById(ids,function(rep){
       $scope.rep=rep;
    });
}

Can anyone help me?

1 个答案:

答案 0 :(得分:1)

AngularJS treats the attributes id and data-id as if they are the same.

From the Docs:

Normalization1

Angular normalizes an element's tag and attribute name to determine which elements match.

The normalization process is as follows:

Strip x- and data- from the front of the element/attributes. Convert the :, -, or _-delimited name to camelCase.

Choose attribute names that don't normalize to the same thing.


Also multiple parameters can be added to the ng-click function.

<button data-pers-id={{pers.id}} ng-click='getMyId(pers.id, $event)'>
    {{pers.name}}
</button>

The getMyId function can get the id information directly from the model data. No need to extract it from the $event object.