2013-07-19 25 views
0

如果我有一個名爲如何使用angular.js指令訪問元素值?

<table> 
    <tr> 
    <td cellDirective>Some cell Value</td> 
    <td cellDirective>Another cell value</td> 
    ... 
    <tr> ... 
<table> 

定義的表格單元格與風格指令通過

myapp = angular.module('myapp', []); 
myapp.directive('cellDirective', function() { 
    return { 
    link: function(scope, element) { 
     console.log(element); 
     element.addClass("coloring-class"); 
    } 
    }; 
}); 

<style> 
    .coloring-class { 
    color: blue; 
    } 
</style> 

我得到控制檯是一個對象的引用有很多不同的屬性,但我無法在每個單元格中找到值。那麼如何訪問元素內的值呢?

回答

0

這只是良好的老式的jQuery:

console.log(element.text()); 
+0

我該如何做到這一點沒有jQuery?我有一個ng-repeat,其中的單元格值表示爲{{cell}},並且此函數返回文本{{cell}}。你可以訪問http://jsbin.com/usecuf/13 – user1876508

+0

所以你的例子與問題有點不同。您可以執行以下兩項操作之一 - 或者使用transclusion(http://docs.angularjs.org/guide/directive)將HTML傳遞到指令中,或者在包含{{cell}}的指令中定義模板。 –

+1

只需指出,Angular的指令文檔非常密集,但示例很準確。在我理解建築指令之前,我花了幾次(很慢)的讀數。 –

1

根據您的JSBin,如果你有定義爲

<td ng-repeat="cell in row" class="spreadsheet" cell="{{ cell }}"> 

細胞可以定義你的指令,因爲

clinApp.directive('cell', function() { 
    return { 
    restrict: 'AE', 
    link: function(scope, element, attrs) { 
     console.log(attrs.cell); 

attrs包含放置指令的當前元素的所有屬性。

+0

這只是返回undefined。您可以檢查我對bin的更改,但我將console.log(attrs.cell)和attrs參數添加到了我的鏈接函數中。 – user1876508