在指令模板中调用函数

时间:2017-11-15 14:58:14

标签: javascript angularjs angularjs-directive angularjs-controller

我有这样的指令

  app.directive('clipChat', ClipChat);

function ClipChat() {
    var strfin ='*';
    var chatTemplate = '<div ng-repeat="message in newarr">   <span ng-if="message.content.slice(-1)==message.star"  ng-click="makeitTodo(message)">i <i class="fa fa-mail-forward "></i></span> '+ '</div>' ;
    var directive = {
        restrict: 'EA',
        template: chatTemplate,
        replace: true,
        scope: {
            messages: "=",
            idSelf: "=",
            idOther: "=",

        },


        link:function ($scope) {

//等等

当我点击控制器内的span元素时,我想调用函数makeitTodo ..

我测试过如下。

app.controller('ChatCtrl',  ["$scope",function($scope){
 $scope.makeitTodo = function(a){
  alert(a);
}
}])

但它不起作用。请帮助我。

1 个答案:

答案 0 :(得分:5)

缺少隔离范围函数绑定

示例小提琴手: https://jsfiddle.net/paka2/9yda0cLk `

angular.module('myApp', []).controller('myCtrl', function($scope) {
    $scope.makeitTodo = function(message) {
    console.log(message);
    }
}).directive('clipChat', function() {
    return {
    restrict: "E",
        scope: { done: '&' },
        template: '<input type="text" ng-model="message">'+
        '<button ng-click="done({message:message})"> click me </button>'
    }
});;

`