2014-05-19 66 views
0

我想獲取元素的屬性值,但返回undefined。如何使用angularjs獲取元素值?

HTML

<button id="myId" ng-click="hi($event)">click me</button> 

JS

$scope.hi = function (e) { 
    var elem = angular.element(e.srcElement); 
    alert(elem.attr("id")); 

} 

爲什麼我得到了一個未定義?

回答

0

$event會將click事件傳遞給你的函數。

對於使用元素本身,您應該使用directive

app.directive('mydirectiver', function() { 
return { 

    link: function(scope,element,attrs){ 

     //element will point to the element 

     //attrs will point to the elements attributes 

    } 

}; 
}); 

我強烈建議Angular docs講授關於指令的講座。他們一開始有點混淆,但你應該能夠快速圍繞這個概念,並從他們的力量中受益。

1

變化e.srcElemente.target

例如:

$scope.hi = function (e) { 

    var elem = angular.element(e.target); 
     alert(elem.attr("id")); 
} 

DEMO

或U可以使用

$scope.hi = function (e) { 
    alert(e.target.id); 
} 

DEMO