我有一个显示投资的视图+另外两个视图是注册新投资的模式,当用户单击“添加”时会显示新模式(由于有两个注册步骤,所以出现了两个模式)。我创建了工厂,该工厂在步骤1和步骤2中使用,以便保留有关注册投资的信息-当您在步骤1和步骤2之间来回切换时,它可以工作。
问题在于,在显示投资的第一个视图中,我有一个图标“ edit”,在其处理程序(编辑方法)中,我将选定的投资分配给了工厂,但是在step1视图中没有任何变化,change。

查看显示的投资:

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;
});


显示注册的step1视图如下

<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松开引用。若要使investment对象不使用update方法创建新变量,可以使用investment / angular.extend方法。此方法不会创建对象的新引用,但可以确保所有对象属性都已更新。

update: function (investment) {
    angular.extend(this.investment, investment);
}

09-16 09:06