gpt4 book ai didi

angularjs - 在不同的元素上使用相同的 Controller 来引用同一个对象

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

我想如果我打了ng-controller="GeneralInfoCtrl"在我的 DOM 中的多个元素上,它们将共享相同的 $scope (或者至少双向绑定(bind)不起作用)。

我想要这样做的原因是因为我在 HTML 的不同部分有不同的只读 View 和关联的模式对话框,并且它们不共享共同的祖先(除了 <body><html> ) .

有没有办法让两个 Controller 引用同一个对象/使数据绑定(bind)在它们之间工作?

<小时/>

对于那些坚持要查看标记的人来说,这里有一些代码,Jade 编写:

   .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')
...

还有我的 Controller :

function GeneralInfoCtrl($scope) {
$scope.client = {
firstName: 'Charlie',
lastName: 'Brown',
birthDate: new Date(2009, 12, 15),
...
}
}

最佳答案

每次 Angular 编译器在 HTML 中找到 ng-controller 时,就会创建一个新的作用域。 (如果您使用 ng-view,每次转到不同的路线时,也会创建一个新的范围。)

如果您需要在 Controller 之间共享数据,通常服务是您的最佳选择。将共享数据放入服务中,并将服务注入(inject)到 Controller 中:

function GeneralInfoCtrl($scope, MyService) {

每个作用域/ Controller 实例都将能够访问共享数据。

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

这是一个fiddle (我没有写)展示了两个 Controller 如何共享数据。

另请参阅AngularJS: How can I pass variables between controllers?
Angularjs: two way data bindings and controller reload .

关于angularjs - 在不同的元素上使用相同的 Controller 来引用同一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14453216/

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