我是一个有角度的新手,试图学习和我有控制器之间传递对象的问题。它的工作原理,如果我有一个数组做Angluarjs控制器之间传递对象
我的JS
var app = angular.module('myApp', []);
app.factory('messages', function(){
var messages = {};
messages.list = [];
messages.add = function(message){
messages.list.push({id: messages.list.length, text: message});
};
return messages;
});
app.factory('portfolio', function(){
var portfolio = {};
portfolio.list = [];
portfolio.add = function(newProperty){
portfolio.list.push(newProperty);
};
return portfolio;
});
app.controller('ListCtrl', function (messages, portfolio){
var self = this;
self.messages = messages.list;
self.portfolio = portfolio.list;
});
app.controller('PostCtrl', function (messages, portfolio){
var self = this;
message = 'property added';
self.addProperty = function(newProperty){
portfolio.add(newProperty);
messages.add(message);
};
});
我的HTML
<div>
<h1>Services</h1>
<div ng-controller="ListCtrl as list">
<div style="text-align: center">
<h2>Initial investment</h2>
<ul class="list">
<input type="hidden" ng-model="newProperty.id" placeholder="id">
<li class="list__item">
<input type="text" class="text-input text-input--transparent" style="width:100%; margin-top:4px;" ng-model="newProperty.pprice" placeholder="Purchase price">
</li>
<li class="list__item">
<input type="text" class="text-input text-input--transparent" style="width:100%; margin-top:4px;" ng-model="newProperty.mv" placeholder="Market value">
</li>
<li class="list__item">
<input type="text" class="text-input text-input--transparent" style="width:100%; margin-top:4px;" ng-model="newProperty.stamp" placeholder="Stamp duty">
</li>
<li class="list__item">
<input type="text" class="text-input text-input--transparent" style="width:100%; margin-top:4px;" ng-model="newProperty.sourcing" placeholder="Sourcing fee">
</li>
<li class="list__item">
<input type="text" class="text-input text-input--transparent" style="width:100%; margin-top:4px;" ng-model="newProperty.legal" placeholder="Legal fee">
</li>
<li class="list__item">
<input type="text" class="text-input text-input--transparent" style="width:100%; margin-top:4px;" ng-model="newProperty.other" placeholder="Other">
</li>
</ul>
</div>
<br />
<p ng-repeat="message in list.messages">{{ message.id }}: {{ message.text }}</p>
<p ng-repeat="prop in list.portfolio">New Item: {{prop.legal}}: {{prop.stamp}} </p>
</div>
</div>
</div>
<div ng-controller="PostCtrl as post">
<input type="button" ng-click="post.addProperty(newProperty) post.newProperty = {}" value="Create"></input>
</div>
所以我知道这个问题是与对象,我发现,我应该使用angular.copy(),但不知道如何使用它与推。
谢谢你的帮助!
为什么创建新元素按钮在与表单输入一样的控制器? –
这只是一个测试页面,想法是让2 conrtroler交谈。 最终会有3-4个带有表单的html页面,但我想使用1个对象。 – nocrack