Javascript AngularJS跨控制器更新文本框
我有以下html:Javascript AngularJS跨控制器更新文本框,javascript,angularjs,shared,controllers,Javascript,Angularjs,Shared,Controllers,我有以下html: <div ng-controller="controller as vm"> <table class="table table-condensed"> <tr> <th>id</th> <th>name</th> <th>address</th> </tr> <tr ng-repeat=
<div ng-controller="controller as vm">
<table class="table table-condensed">
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
</tr>
<tr ng-repeat="item in vm.array" >
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.address}}</td>
<td><button ng-click="vm.edit(item)">pass the value</button></td>
</tr>
</table>
<form>
name <input type="text" ng-model="vm.item.name" />
address <input type="text" ng-model="vm.item.address"/>
</form>
</div>
<div ng-controller="controller as vm" class="container">
<form>
name <input type="text" ng-model="vm.item.name" />
address <input type="text" ng-model="vm.item.address"/>
</form>
</div>
请看这个plunker:
我希望能够在更新第一个表单的同时更新底部第二个表单中的文本
我正在处理的应用程序有两个面板。左边是列表,右边是表单。单击行按钮时,我希望填充右侧的表单。右侧的html位于单独的文件中。共享同一个控制器并不能做到这一点,但我可以使用不同的控制器,但不确定哪种方法最好,或者如何实现。我需要服务吗
谁能给我指出正确的方向吗
更新:
我最终得到的解决方案如下:
我尝试了服务,但在更新服务时第二个视图模型没有更新。所以我尝试了广播和$emit,效果很好。我知道使用$rootscope不是一个好主意。因此,当我有更多时间时,我将寻找另一种方法。对于组件通信,您应该使用服务或创建带有输入和输出参数绑定的角度(1.5+)。组件将与负责维护状态的父控制器通信 app.html中的html将包含类似于以下内容的内容 app.html
<section>Sidebar
<p>{{vm.item.name}}</p>
</section>
<section>Main
<my-form-component item="vm.item" on-update="vm.onUpdate($event)"> </my-form-component>
<section>
form.component.js
app.controller('controller',function($scope) {
var vm = this;
vm.item = {name:''};
vm.onUpdate = function(item) {
vm.item = item;
}
});
app.component('myFormComponent', {
templateUrl: 'myFormTemplate.html',
bindings: {
item: '<',
onUpdate:'&'
},
controller: function() {
this.$onChanges = function(changeObj) {
this.onUpdate(changeObj.item); //output item to parent
}
}
});
app.component('myFormComponent'{
templateUrl:'myFormTemplate.html',
绑定:{
item:'为什么不能共享同一个控制器?有两个html文件,我希望每个文件中都有一个控制器。我不负责结构,也无法更改它。我最终使用以下方法解决了这个问题:谢谢,目前正在尝试使用服务。将签出组件。不知道这些。没问题。一定要签出组件t架构,因为您将在Angular 2或4中使用它,或者无论它现在叫什么。它也使您的应用程序更容易升级,因为它不依赖范围。
app.component('myFormComponent', {
templateUrl: 'myFormTemplate.html',
bindings: {
item: '<',
onUpdate:'&'
},
controller: function() {
this.$onChanges = function(changeObj) {
this.onUpdate(changeObj.item); //output item to parent
}
}
});