繁体   English   中英

触发以单击angular.js中的html元素

[英]Trigger to click on an html element in angular.js

我目前有一个指令。 当我使用“单击以编辑”指令单击元素时,将显示一个文本字段以编辑内容。

在此处输入图片说明 在此处输入图片说明

我想要当我单击按钮时,这种现象继续发生。 我需要单击按钮时,它等效于单击指令。 我该如何实现?

    <label>Sprint name:</label> <div click-to-edit type="inputText" ng-model="sprintName"></div>
    <br/>
    <input type='button' value='trigger Directive' ng-click='triggerDirective()'>
   </div>

https://codepen.io/anon/pen/JNQRLY

要实现您必须执行的操作,可以使用角度事件也可以通过隔离范围共享对象并向其中添加功能

例子:

1-使用Angularjs事件:PLUNKER

HTML:

<div click-to-edit></div>
<button type="button" ng-click="item.toggle()">Toggle from Controller</button>

控制器:

app.controller('MainCtrl', function($scope) {
    $scope.toggle = function(){
        //Emit the event
        $scope.$broadcast('app.myEvent');
    };
});

指示:

app.directive('clickToEdit', function() {
    return {
        restrict: 'A',
        template: `
            <div ng-show="editState">
                <div>
                    <input type="text"/>
                    <button type="button" ng-click="item.toggle()">Cancel</button>
                </div>
            </div>
        `,
        link: function (scope, element, attrs) {
            scope.editState = false;

            scope.toggle = function () {
                scope.editState = !scope.editState;
            }

            //Listen and handler the event
            scope.$on('app.myEvent', function(event){
                scope.toggle();
            });
        }
    }
});

2-通过隔离范围共享对象:PLUNKER

HTML:

<div click-to-edit item="item"></div>
<button type="button" ng-click="item.toggle()">Toggle from Controller</button>

控制器:

app.controller('MainCtrl', function($scope) {
    $scope.item = {};
});

指示:

app.directive('clickToEdit', function() {
    return {
        restrict: 'A',
        scope: {
            item: '='
        }
        template: `
            <div ng-show="editState">
                <div>
                    <input type="text"/>
                    <button type="button" ng-click="item.toggle()">Cancel</button>
                </div>
            </div>
        `,
        link: function (scope, element, attrs) {
            scope.editState = false;

            //Here you add the function to the isolate scope 'item' variable
            scope.item.toggle = function () {
                scope.editState = !scope.editState;
            }
        }
    }
});

修改指令,在其中添加按钮控件的click bind事件。 因此,在调用伪指令时,它将绑定按钮上的click事件。 希望这可以帮助 !

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM