2015-05-19 75 views
1

我想開發一個指令,其中我必須有一個可點擊的按鈕,點擊觸發控制器功能。ng-click在指令中不起作用

這裏是我的代碼

'use strict'; 

/*global d3:false */ 

angular.module('myApp').directive('legends', function() { 
return { 
    restrict: 'E', 
    scope: { 
    service: '=', 
    buttonClick : '&' 
    }, 
    replace: true, 

    link: function(scope, element, attrs) { 

    function main(data) { 
     var format = d3.time.format('%d %b %y'), 
     str = '<div>'+ 
     '<div>'+ 
     '<span>A</span>'+ 
     '<span>' + format(data[0]) + '</span>'+ 
     '<span>'+ data[1].toFixed(2) +'</span></div>'+ 
     '<div>'+ 
     '<span ng-click="buttonClick()"></span>'+ 
     '</div>'+ 
     '<div>'+ 
     '<span>B</span>'+ 
     '<span>' + format(data[2]) + '</span>'+ 
     '<span>'+ data[3].toFixed(2) +'</span></div></div>'; 
     element.html(str); 
    } 

    //********************************************************************* 
    scope.$watchCollection('service', function(data) { 
     if (!angular.isUndefined(data) && data.length === 4) { 
     main(data); 

     }   
    }); 
    } 

}; 

});

我在另一篇文章中讀到,我必須通過函數的引用作爲屬性,這是我所做的,但仍然沒有被觸發。

Ctrl鍵:

angular.module('myApp') 
.controller('ctrl', 
    function() { 
     $scope.switchObjects = function() { 
      console.log('done'); 
     } 
    } 
); 

謝謝大家:)

回答

0

我可能會錯過一些事,但在你的指令,你的函數被調用buttonClick()並在控制器switchObjects

+0

呀buttonClick是取switchObjects參考爲了調用使用buttonClick控制器功能的屬性() – Dgn

0

在將元素注入元素之前,需要編譯HTML字符串。

像這樣做,而不是:

.directive('myCustomer', function() { 

    function postlink(scope, elem, attrs) { 
     scope.buttonClick = function() { 
      console.log("Button clicked"); 
     } 
    } 

    return { 
    link: postlink, 
    template: '<html>PUT HTML HERE</html>' 
    }; 
});