我有一个显示投资的 View +另外两个 View ,它们是注册新投资的模式,当用户单击“添加”时显示(由于注册的两个步骤,所以有两个模式)。我创建了在步骤 1 中使用的工厂,然后在步骤 2 中使用它,以便保留有关正在注册的投资的信息 - 当您在步骤 1 和步骤 2 之间来回切换时,它会起作用。
问题是,在显示投资的第一个 View 中,我有图标“编辑”,并且在其处理程序(编辑方法)中,我将选定的投资分配给工厂,但第 1 步 View 中没有反射(reflect)任何更改,唉。
查看显示的投资:
var module = angular.module("application", []);
module.controller("investmentsController", function ($scope, investmentsFactory, newInvestmentFactory) {
$scope.edit = function (id) {
for (var i = 0; i < $scope.Investments.length; i++) {
if ($scope.Investments[i].Id == id) {
newInvestmentFactory.update($scope.Investments[i]);
}
}
$("#addInvestmentStep1Modal").modal("show");
};
});
查看注册步骤1
var module = angular.module("application");
module.factory("newInvestmentFactory", function () {
return {
investment: {
Name: "",
Description: "",
Category: "",
InterestRate: "",
Duration: "",
AmountRange: "",
Url: "",
Subscription: 0,
PaymentType: "",
Icon: ""
},
update: function (investment) {
this.investment = investment;
}
};
});
module.controller("newInvestmentStep1Controller", function ($scope, newInvestmentFactory) {
$scope.Investment = newInvestmentFactory.investment;
});
查看注册步骤2
var module = angular.module("application");
module.controller("newInvestmentStep2Controller", function ($scope, newInvestmentFactory) {
$scope.Investment = newInvestmentFactory.investment;
});
显示注册的第 1 步 View 如下
<form id="newInvestmentStep1Form" class="form-horizontal">
<div class="input-group">
<span class="input-group-addon input-group-addon-register">Name</span>
<input id="Name" name="Name" type="text" class="form-control" ng-model="Investment.Name" required title="Pole wymagane" />
</div>
将新对象分配给工厂的对象(newInvestmentFactory.investment)似乎不起作用,但是当我将全新的值分配给工厂的某些属性时,例如
newInvestmentFactory.investment.Name = "name"
然后它会正确显示值。
最佳答案
我只能怀疑newInvestmentFactory
的update
方法代码。它将investment
对象重新分配给新的investment
对象,例如this.investment = Investment
。通过该行,新的投资对象被创建,旧的投资对象释放了引用。要保持 Investment 对象不在更新方法中创建新变量,您可以使用 Angular.extend/Angular.merge 方法。此方法不会创建对象的新引用,但它确保所有对象属性均已更新。
update: function (investment) {
angular.extend(this.investment, investment);
}
关于javascript - Angular.js 工厂对象未在 View 中刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43704781/