2016-09-08 19 views
1

ディレクティブのリンク機能をいつ呼び出すべきかを指定する方法が不思議です。AngularJsディレクティブがクリック時にリンク機能を呼び出す

現在、私は次のコードを持って:あなたは、私は私が望むものの擬似っぽいコードをコメントアウトしている見ることができるように

<my-directive username="abc"></my-directive>

module.directive("myDirective", [{ 
 
    restrict: "A", 
 
    link($scope, element, others) { 
 
    //if element.clicked() { 
 
    // console.log("you clicked me"); 
 
    //} 
 
    } 
 
}]);

これを行うには、element.onClick = functのようなことが可能であることがわかりましたイオン(){}。しかし、要素がクリックされたときにこれはまだ呼び出されていないようです。

おかげ

答えて

2

はこれを試してください:あなたがこれを使用できるように

element.on('click', function() {}); 

角度の用途は、jQuery Liteで構築します。

+0

私はこれを試してみましたが、期待通りに動作しませんでした。 – SwimmingG

+0

あなたは正しいです、それは私のせいです。私は私の答えを編集しました。 – RWAM

+0

まあまあまあ、同じ、私の答えを削除します! – SwimmingG

0

この

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

 
app.controller('MainCtrl', function($scope) { 
 

 
    $scope.abc = 'abc'; 
 
    
 
}); 
 

 

 

 
app.directive('myDirective', function() { 
 
    return { 
 
    restrict: 'E', 
 
    scope: { 
 
     username: '=' 
 
    }, 
 
    link:link, 
 
    template: '<div>Click Here</div>' 
 
    }; 
 
    function link(scope,elem,others){ 
 
    
 
    elem.bind('click', function() { 
 
     console.log('on click'); 
 
    }); 
 
    
 
    } 
 
});
<head> 
 
    <meta charset="utf-8" /> 
 
    <title>AngularJS Plunker</title> 
 
    <script>document.write('<base href="' + document.location + '" />');</script> 
 
    <link href="style.css" rel="stylesheet" /> 
 
    <script data-semver="1.4.9" src="https://code.angularjs.org/1.4.12/angular.js" data-require="[email protected]"></script> 
 
    <script src="app.js"></script> 
 
    </head> 
 

 
    <body ng-app="plunker" ng-controller="MainCtrl"> 
 
    <my-directive username="abc"></my-directive> 
 
    </body>

0

を試してみてください、あなたはまた、このようにしてみてください!

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

 
app.controller('MainCtrl', function($scope) { 
 

 
    $scope.abc = 'abc'; 
 
    
 
}); 
 

 

 

 
app.directive('myDirective', function() { 
 
    return { 
 
    restrict: 'E', 
 
    scope: { 
 
     username: '=' 
 
    }, 
 
    link:link, 
 
    template: '<div ng-click="click()">Click Here</div>' 
 
    }; 
 
    function link(scope,elem,others){ 
 
    
 
    scope.click = function() { 
 
     console.log('on click', scope.username);  
 
    } 
 
    } 
 
});
<head> 
 
    <meta charset="utf-8" /> 
 
    <title>AngularJS Plunker</title> 
 
    <script>document.write('<base href="' + document.location + '" />');</script> 
 
    <link href="style.css" rel="stylesheet" /> 
 
    <script data-semver="1.4.9" src="https://code.angularjs.org/1.4.12/angular.js" data-require="[email protected]"></script> 
 
    <script src="app.js"></script> 
 
    </head> 
 

 
    <body ng-app="plunker" ng-controller="MainCtrl"> 
 
    <my-directive username="abc"></my-directive> 
 
    </body>

関連する問題