2016-03-23 158 views
0

我有简单的指令,像这样:Angularjs指令创建点击事件

angular.module('docsTemplateUrlDirective', []) 
    .controller('Controller', ['$scope', function($scope) { 
     $scope.customer = { 
     name: 'Naomi', 
     address: '1600 Amphitheatre' 
     }; 

$scope.clicke = function(){ 
alert('test'); 
}; 

    }]) 
    .directive('myCustomer', function() { 
     return { 
     templateUrl: 'my-customer.html' 
     }; 
    }); 

的index.html

<div ng-controller="Controller"> 
    <div my-customer click-event='clicke()'></div> 
</div> 

我-customer.html

Name: {{customer.name}} Address: {{customer.address}} 
<button>click</button> 

,我想创建点击按钮的事件,然后在我的控制器 中使用此事件。 但我不知道该怎么做。 帮我看看。非常感谢。

+0

您可以用'NG-click',不是吗? – aprok

+1

整个指令应该是可点击的吗?如在,它是一个元素指令? – ellitt

+1

'ng-click =“clicke($ event)”' – fracz

回答

1

我会建议使用的东西Angular已经给你:ng-click

这里有一个JSBin的例子,我为你所做的:

<div ng-controller="Controller"> 
    <div my-customer ng-click='clicke()'></div> 
</div> 

如果你点击了该指令,它应该是这样的:

enter image description here

+0

好的,谢谢但是如果我需要使用更多的元素并在点击后得到一些id或名字。我想使用像标签菜单和动态构建它的指令。然后点击某个项目(1,3 .. xxx)获得他的ID。我不知道该怎么做。 –

1

您可以使用ng-repeat遍历一组客户,然后让您的ng-click函数获取与客户(阵列中的索引)相关的参数...

<div ng-repeat="customer customers track by $index" ng-click="myClickHandler(index)"> 
    {{customer}} 
</div> 
1

我会建议以下解决方案。工作示例可以在这里找到 - @sumit Plunker
下面是一个代码示例:

angular.module('docsTemplateUrlDirective', []) 
    .controller('Controller', ['$scope', function($scope) { 
    $scope.customer = { 
     name: 'Naomi', 
     address: '1600 Amphitheatre' 
    }; 

    $scope.clicke = function(evt) { 
     alert('test'); 
    }; 

    }]) 
    .directive('myCustomer', function($parse) { 
    return { 
     restrict: 'A', 
     scope: true, 
     templateUrl: 'my-customer.html' 
    } 
    }) 
    .directive('clickEvent', function($parse) { 
    return { 
     restrict: 'A', 
     scope: true, 
     link: function(scope, el, attrs) { 
     var expressionHandler = $parse(attrs.clickEvent) 
     el.find('#btnSubmit').on('click', function(e) { 
      expressionHandler(scope); 
     }) 
     } 
    } 
    });