2013-02-14 19 views
0

我試圖編寫一個指令來創建一組按鈕。爲了在屏幕上突出顯示數據,這些按鈕將用作開/關切換。

的指令如下:

angular.module('directives', []) 
.directive('toggleButtons', function() { 
    return { 
    restrict: 'E', 
    scope: { data: '='}, 
    controller: function($scope) { 
     $scope.toggle = function(data) { 
     alert(data); 
     }; 
    }, 
    template: "<button class='btn' " + 
       //"ng-class='{active: option == model}'" + 
       "ng-repeat='datum in data' " + 
       "ng-click=\"toggle({{datum['id']}})\">{{datum['name']}}" + 
       "</button>" 
    }; 
}); 

現在,據我所知,以確保datum['id'']片被Angularjs我需要運行$compile()解釋,但我不知道如何實現這一點。請有人展示如何改變這個代碼來實現這個目標? (同樣,如果這不是正確的方法,請讓我知道)。謝謝!

回答

2

你真的很親密。你不需要在花括號中包裝datum['id']調用,因爲角爲你編譯模板。

所以,如果您只是將其更改爲ng-click='toggle(datum.id)',它將會正常工作,如you can see here

+0

太棒了,感謝您的幫助。 – jgm 2013-02-14 22:15:40

0
I am meeting a similar issue that the variable is undefined after using $compile(template)($scope); 

For example: 
1: var pendingObjDiv = $("<div class="open-detail-btn" ng-click="goToFormPage(aaa)"></div>"); 
2: var pendingTemplate = angular.element(pendingObjDiv); 
    var pendingElement = $compile(pendingTemplate)($scope); 
    pendingRowList.append(pendingElement); 
3: $scope.goToFormPage = function(str){}; at this step, the variable str is undefined.