2016-08-08 33 views
0

我不知道如何使用ng-click從我的指令中調用函數。如何從我的angular-js指令中單擊一個函數?

這是我的HTML的例子:

<div> 
    <directive-name data="exemple"> 
     <button class=btn btn-primary type="submit" ng-click="search()"> 
    </directive-name> 
</div> 

這是我的JavaScript的例子:提前

... 
.directive('directiveName', ['exempleService', function(exempleService) { 
    function link(scope, element, attrs) { 

     scope.search = function() { 
      console.log("this is working") 
     }; 
    }; 

    return { 
     link: link, 
     restrict: 'E', 
     scope: {data:'=', 
     search:'&'} 
    } 

}]); 

謝謝! :)

回答

1

你必須創建一個directive其中包括指令模板(無論是作爲HTML或外部文件)內button

VIEW

<div ng-app="app"> 
    <directive-name data="exemple"></directive-name> 
</div> 

DIRECTIVE

var app = angular.module('app', []) 

app.directive('directiveName', function() { 
    return { 
    restrict: 'E', 
    link: function(scope, element, attrs) { 
     scope.search = function() { 
     alert('boe'); 
     } 
    }, 
    template: '<button class=btn btn-primary type="submit" ng-click="search()">CLICK</button>' 

    } 
}) 

FIDDLE

+0

非常感謝您的快速和工作答案! :) –

0

您的按鈕應該是在你的指令模板

.directive('directiveName', ['exempleService', function(exempleService) { 
    function link(scope, element, attrs) { 

     scope.search = function() { 
      console.log("this is working") 
     }; 
    }; 

    return { 
     link: link, 
     restrict: 'E', 
     template: '<div><button class=btn btn-primary type="submit" ng-click="search()"></div>' 
     scope: {data:'=', 
     search:'&'} 
    } 

}]); 
相關問題