gpt4 book ai didi

javascript - 触发点击 angular.js 中的 html 元素

转载 作者:行者123 更新时间:2023-12-03 04:12:59 25 4
gpt4 key购买 nike

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

enter image description here enter image description here

我希望当我单击按钮时,此行为继续发生。我需要当单击按钮时,相当于单击指令。我怎样才能实现这个目标?

    <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

最佳答案

要实现您必须做的事情,您可以使用 angular eventsyou can share an object through isolate scope and add a function to it

示例:

1- 使用 Angularjs 事件: ( PLUNKER )

HTML:

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

Controller :

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>

Controller :

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

关于javascript - 触发点击 angular.js 中的 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44251699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com