angularjs 指令上的 ng-click 属性 [英] ng-click attribute on angularjs directive
问题描述
我认为在开箱即用的指令上使用众所周知的角度属性应该很容易.
例如,如果我的指令的名称是 myDirective,我想这样使用它:
<my-directive ng-click="doSomething()"><my-directive>
而不是像下面的例子那样需要定义一个自定义的点击属性(onClick)
<my-directive on-click="doSomething()"><my-directive>
似乎 ng-click 可以工作,但是您也需要在指令标签上指定 ng-controller ,这是我不想要的.我想在周围的 div 上定义控制器
是否可以将 ng-click 指令与在父 html 元素上定义的控制器一起使用?
这里是更新的代码.也许这就是您要找的.p>
HTML:
<div data-ng-controller="MyController"><my-directive data-ng-click="myFirstFunction('Hallo')"></my-directive><my-directive data-ng-click="mySecondFunction('Hi')"></my-directive>
角度:
var app = angular.module('myApp', []);app.directive('myDirective', function(){返回 {限制:'EA',替换:真的,范围: {eventHandler: '&ngClick'},模板:'<div id="holder"><button data-ng-click="eventHandler()">调用自己的函数</button></div>'};});app.controller('MyController', ['$scope', function($scope) {$scope.myFirstFunction = 函数(味精){alert(msg + '!!!第一个函数调用!');};$scope.mySecondFunction = 函数(味精){alert(msg + '!!!第二个函数调用!');};}]);
编辑
检查我在 jsFiddler 中制作的解决方案是您要找的吗?
http://jsfiddle.net/migontech/3QRDt/1/
I think it should be easy to use the well known angular attributes on a directive out of the box.
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>
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>
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
Is it possible to use ng-click on a directive together with a controller defined on a parent html element?
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>
Angular:
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!');
};
}]);
Edit
Check solution that I made in jsFiddler is that what you were looking for?
http://jsfiddle.net/migontech/3QRDt/1/
这篇关于angularjs 指令上的 ng-click 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!