2017-05-02 5 views
1

このコードでは、ng-clickをカスタムエレメントディレクティブに設定し、「Worked from directive!」というアラートを確信しています。ユーザーがレンダリングされたテキストをクリックするとポップアップするはずです。それは動作しません。Angular 1.xのカスタムエレメントディレクティブのng-clickの設定方法

jQuery-liteを使用してイベントリスナーをelemオブジェクトにアタッチすることはできますが、なぜ私のコードが機能しないのか不思議で、ng-clickをこの方法で使用できるかどうかは不思議です。

https://jsbin.com/xobagigasi/1/edit?html,js,console,output

あなたがイベントをクリックしてバインドすることができ

var myApp = angular.module("myApp",[]); 

function myCustomDirective() { 

    return { 

     template: '<h1>This text is from my custom directive.Click me and an alert should appear</h1>', 

     scope: {}, 

     link: function(scope, elem, attrs) { 

      //________________________________BEGIN 

      scope.runAlert = function() { 
       alert("Worked from directive!"); 
      }; 
      //_______________________________END 
     } 
    } 
} 

myApp.directive("myCustomElement", myCustomDirective); 

答えて

0

HTML

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width"> 
    <title>JS Bin</title> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script> 
</head> 
<body ng-app="myApp"> 

    <my-custom-element ng-click="runAlert()"></my-custom-element> 


    </body> 
</html> 

JavaScriptが指令へ

var myApp = angular.module("myApp",[]); 
 
myApp.controller("ctrl",function($scope){ 
 
$scope.runAlert = function() { 
 
      alert("Worked from directive!"); 
 
      } 
 
}); 
 
function myCustomDirective() { 
 

 
    return { 
 

 
     template: '<h1>This text is from my custom directive.Click me and an alert should appear</h1>', 
 
    
 
     scope: { 
 
     }, 
 

 
     link: function(scope, elem, attrs) { 
 
     elem.bind('click',function(){ 
 
       alert("Worked from directive!"); 
 
     }) 
 

 
     } 
 
    } 
 
} 
 

 
myApp.directive("myCustomElement", myCustomDirective);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script> 
 

 
<div ng-app="myApp"> 
 
    <my-custom-element ></my-custom-element> 
 
    </div>

0

ここでの問題は、ディレクティブとng-clickで述べた関数はディレクティブを呼び出している親スコープ中に存在すべきです。ディレクティブの中でそれを保つために

二つの方法:

  • あなたはディレクティブの内側からアクセスしたい場合は、scope.$parent.runAlert = function() {....}

    JSBin Example

  • 使用親スコープの機能にアクセスするために$parentを使用することができますelement.bind内のlinkイベントをディレクティブ要素にバインドする関数
0
<my-custom-element></my-custom-element> 

function myCustomDirective() { 

    return { 

     template: '<h1>This text is from my custom directive. 
       <label ng-click="runAlert()">Click me </label> and an alert 
       should appear</h1>', 
     scope: {}, 

     link: function(scope, elem, attrs) { 

      scope.runAlert = function(){ 
       alert("Worked from directive!"); 
      } 

     } 
    } 
} 

myApp.directive("myCustomElement", myCustomDirective); 
関連する問題