如何在Angular 1.x中设置ng-click自定义元素指令

时间:2017-05-02 08:24:12

标签: javascript angularjs

在这段代码中,我设置了ng-click到一个自定义元素指令,我确信警告“工作于指令!”应该在用户单击呈现的文本时弹出。它不起作用。

我知道我可以使用JQuery-lite将事件监听器附加到elem对象,但我仍然很好奇为什么我的代码不起作用,并且是否可以使用ng-click这样。

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

HTML

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);

的JavaScript

jdeps

3 个答案:

答案 0 :(得分:0)

您可以将click事件绑定到指令

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

&#13;
&#13;
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);
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这里的问题是<?php $input = ['BE001 FIRST', 'BE01 SECOND', 'SV001 THIRD', 'BE1234 FOURTH']; $output = []; array_walk($input, function(&$entry) use (&$output) { if (preg_match('/BE\d{3}([^\d]|$)/', $entry)) { $output[] = $entry; } }); print_r($output); 中提到的函数,指令应该出现在调用该指令的父作用域中。

将其保持在指令范围内的两种方法:

  • 如果您想从指令内部访问它,可以使用Array ( [0] => BE001 FIRST ) 访问父作用域的函数ng-click

    JSBin Example

  • $parent函数中使用scope.$parent.runAlert = function() {....}将事件绑定到指令元素

答案 2 :(得分: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);