angularjs – 在不同的元素上使用相同的控制器来引用同一个对象

前端之家收集整理的这篇文章主要介绍了angularjs – 在不同的元素上使用相同的控制器来引用同一个对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想如果我在我的DOM中的多个元素上打了ng-controller =“GeneralInfoCtrl”,他们将共享相同的$范围(或至少双向绑定不工作)。

我想这样做的原因是因为我有不同的只读视图和在HTML的非常不同的部分中的相关模态对话,并且它们不共享公共祖先(除了< body>和< html>)。

有没有办法让两个控制器引用相同的对象/使数据绑定在它们之间工作?

这里有一些代码,坚持认为看到标记,写在玉:

.client-Box(ng-controller="GeneralInfoCtrl")
        .Box-header
            .Box-title
                h5 General Information
            .Box-buttons
                button.btn.btn-small(data-target='#editGeneralInfo',data-toggle='modal',data-backdrop='static') <i class="icon-pencil"></i> Edit
        .Box-body
            table.table.table-tight.table-key-value
                tr
                    th Name
                    td {{client.fullName()}}
                tr
                    th Also Known As
                    td {{client.aka}}
                tr
                    th Birth Date
                    td {{client.birthDate|date:'mediumDate'}}
    ...

#editGeneralInfo.modal.hide.fade(ng-controller="GeneralInfoCtrl")
    .modal-header
        button.close(type='button',data-dismiss='modal') &times;
        h3 Edit General Information
    .modal-body
        form.form-horizontal.form-condensed
            .control-group
                label.control-label First Name
                .controls
                    input(type='text',placeholder='First Name',ng-model='client.firstName')
            .control-group
                label.control-label Last Name
                .controls
                    input(type='text',placeholder='Last Name',ng-model='client.lastName')
            .control-group
                label.control-label Also Known As
                .controls
                    input(type='text',placeholder='AKA',ng-model='client.aka')
            .control-group
                label.control-label Birth Date
                .controls
                    input(type='text',placeholder='MM/DD/YYYY',ng-model='client.birthDate')
...

我的控制器:

function GeneralInfoCtrl($scope) {
    $scope.client = {
        firstName: 'Charlie',lastName: 'Brown',birthDate: new Date(2009,12,15),...
    }
}
每次Angular编译器在HTML中找到ng-controller时,都会创建一个新的作用域。 (如果使用ng-view,则每次转到其他路由时,都会创建一个新作用域。)

如果你需要在控制器之间共享数据,通常一个服务是你最好的选择。将共享数据放入服务,并将服务注入到控制器中:

function GeneralInfoCtrl($scope,MyService) {

每个范围/控制器实例将能够访问共享数据。

请注意,服务是单例,因此您的共享数据只有一个实例。

这里是一个fiddle(我没有写它)显示两个控制器如何共享数据。

参见pass variables between controllersAngularjs: two way data bindings and controller reload

原文链接:https://www.f2er.com/angularjs/146372.html

猜你在找的Angularjs相关文章