在angularjs指令NG-单击属性 [英] ng-click attribute on angularjs directive

查看:185
本文介绍了在angularjs指令NG-单击属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这应该很容易在指令中使用众所周知的角属性的开箱。

I think it should be easy to use the well known angular attributes on a directive out of the box.

例如,如果我的指令的名称是myDirective我想用这种方式:

For example if the name of my directive is myDirective I would like to use it this way:

<div ng-controller="myController">
   <my-directive ng-click="doSomething()"><my-directive>
</div>

而不是需要定义一个自定义属性点击(的onClick),如下

instead of needing to define a custom click attribute (onClick) as in the example below

<div ng-controller="myController">
   <my-directive on-click="doSomething()"><my-directive>
</div>

看来,NG-点击可以工作,但那么你就需要太多,我不想在指定的指令标签NG-控制器。我想定义在周围的div控制器

It seems that ng-click can work, but then you need to specify ng-controller on the directive tag too which I don't want. I want to define the controller on a surrounding div

是否有可能使用的指令连同父html元素上定义的控制器NG-点击?

Is it possible to use ng-click on a directive together with a controller defined on a parent html element?

推荐答案

下面更新code。也许这就是你所期待的。

Here is updated code. Maybe is this what you were looking for.

HTML:

<div data-ng-app="myApp">
    <div data-ng-controller="MyController">
        <my-directive data-ng-click="myFirstFunction('Hallo')"></my-directive>
        <my-directive data-ng-click="mySecondFunction('Hi')"></my-directive>
    </div>
</div>

角:

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

app.directive('myDirective', function(){
    return {
        restrict: 'EA',
        replace: true,
        scope: {
            eventHandler: '&ngClick'
        },
        template: '<div id="holder"><button data-ng-click="eventHandler()">Call own function</button></div>'
    };
});

app.controller('MyController', ['$scope', function($scope) {
    $scope.myFirstFunction = function(msg) {
         alert(msg + '!!! first function call!');   
    };
    $scope.mySecondFunction = function(msg) {
         alert(msg + '!!! second function call!');   
    };
}]);

修改

这是我在做jsFiddler检查的解决办法是什么你要找的人?

Check solution that I made in jsFiddler is that what you were looking for?

http://jsfiddle.net/migontech/3QRDt/1/

这篇关于在angularjs指令NG-单击属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆