如何从作为可重用组件的指令公开公共 API?

编程入门 行业动态 更新时间:2024-10-07 10:14:42
本文介绍了如何从作为可重用组件的指令公开公共 API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在 angular 中有一个可重用组件的指令,公开可从控制器访问的公共 API 的最佳实践是什么?因此,当组件有多个实例时,您可以从控制器访问

Having a directive in angular that is a reusable component, what is the best practice to expose a public API that can be accessed from the controller? So when there are multiple instances of the component you can have access from the controller

angular.directive('extLabel', function {
    return {
        scope: {
            name: '@',
            configObj: '='
        },
        link: function(scope, iElement, iAttrs) {
            // this could be and exposed method
            scope.changeLabel = function(newLabel) {
                scope.configObj.label = newLabel;
            }
        }
    }
});

然后当有:

<ext-label name="extlabel1" config-obj="label1"></ext-label>
<ext-label name="extlabel2" config-obj="label2"></ext-label>
<ext-label name="extlabel3" config-obj="label3"></ext-label>

如何在控制器中访问 extLabel2 的 scope.changeLabel?

How can I get the access the scope.changeLabel of extLabel2 in a controller?

有意义吗?

推荐答案

这对您有用吗?

angular.directive('extLabel', function() {
    return {
        restrict: 'E',
        scope: {
            api: '='
        },
        link: function(scope, iElement, iAttrs) {
            scope.api = {
                    doSomething: function() { },
                    doMore: function() { }
                };
        }
    };
});

来自包含父级

<ext:label api="myCoolApi"></ext:label>

在控制器中

$scope.myCoolApi.doSomething();
$scope.myCoolApi.doMore();

这篇关于如何从作为可重用组件的指令公开公共 API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 16:51:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1007909.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指令   组件   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!