如何在视图中多次正确使用相同的AngularJS 1.5组件? [英] How to properly use the same AngularJS 1.5 component multiple times in a view?

查看:28
本文介绍了如何在视图中多次正确使用相同的AngularJS 1.5组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AngularJS 1.5的新组件创建一组小部件.问题是,当多次使用相同的小部件时,它们以某种方式共享其控制器或作用域.我认为关于组件的一件事是它们的范围是完全隔离的?

I'm creating a set of widgets with AngularJS 1.5's new components. The problem is, when using the same widget multiple times, they somehow share their controller or scope. I thought one of the things about components was that their scope is completely isolated?

我的主要HTML模板包含小部件:

My main html template which hold the widgets:

<widget-list
    title="Books"
    class="col-xs-12 col-md-4">
</widget-list>

<widget-list
    title="Movies"
    class="col-xs-12 col-md-4">
</widget-list>

<widget-list
    title="Albums"
    class="col-xs-12 col-md-4">
</widget-list>

我的窗口小部件模板:

<div class="widget widget-list">
    <div class="panel b-a">

        <div class="panel-heading b-b b-light">
            <h5>{{$widget.title}}</h5>
            <div class="pull-right">
                <button type="button" class="btn btn-default btn-sm" ng-click="$widget.doSomething()">
                    Do something
                </button>
            </div>
        </div>

        <div class="panel-content">
            {{$widget.content || 'No content'}}
        </div>

    </div>
</div>

我的小部件组件:

app.component('widgetList', {
    templateUrl: 'template/widget/widget-list.html',
    bindings: {
        title   : '@',
    },
    controllerAs: '$widget',
    controller: function($timeout) {

        $widget = this;

        console.log('Title on init: ', $widget.title)

        $timeout(function() {
            console.log('Title after 3 seconds: ', $widget.title)
        }, 3000)

        $widget.doSomething = function() {
            $widget.content = "Something";
        }
    }
});


运行代码时,控制台如下所示:


When running my code, this is what my console looks like:

Title on init: Books
Title on init: Movies
Title on init: Albums
(3) Title after 3 seconds: Albums


渲染后,所有三个小部件在其模板中均显示无内容.但是,当单击三个小部件之一中的 doSomething()按钮时,只有最后一个小部件的内容才会更新为 Something .


Also after rendering, all three widgets display No content in their template. But, when clicking the doSomething() button in either one of the three widgets, only the content of the last widget updates to Something.

这是怎么回事?为什么我的组件没有被隔离"?

What is happening here? Why are my components not 'isolated'?

推荐答案

好像您在这里有一个名为$ widget的全局变量,请尝试以下操作:

Looks like you have a global variable called $widget here, try this:

var $widget = this;

代替

$widget = this;

由于$ widget变量持有对最近初始化的控制器的引用,在本例中为对第三个组件的控制器的引用,因此会造成混乱.

It creates a mess since the $widget variable holds a reference to the controller that has been recently initialized, in this case to the controller of the third component.

这篇关于如何在视图中多次正确使用相同的AngularJS 1.5组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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