簡體   English   中英

AngularJS指令創建點擊事件

[英]Angularjs directive create click event

我有一個簡單的指令,像這樣:

    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>

my-customer.html

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

我想為單擊按鈕創建事件,然后在控制器中使用此事件。 但是我不知道該怎么做。 請幫助我。 非常感謝。

我建議使用Angular已經給您的東西: ng-click

這是我為您提供的一個JSBin示例:

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

如果單擊該指令,則它應如下所示:

在此處輸入圖片說明

您可以使用ng-repeat遍歷一系列客戶,然后讓ng-click函數采用與正在顯示的客戶(數組中的索引)相關的參數...

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

我建議以下解決方案。 一個有效的例子可以在- @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);
        })
      }
    }
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM