Angular.js工厂对象未在视图中刷新



我有单个视图显示投资 另外两个是注册新投资的模式,这些投资是在用户点击'添加'''(两种模式下的两个模式(时显示的。我创建了在步骤1中使用的工厂,然后在Step2中使用,以保留有关正在注册的投资的信息 - 当您在STEP1和Step2之间切换时,它可以正常工作。
问题在于,在显示投资的第一个视图中,我拥有图标"编辑",并且在其处理程序(编辑方法(中,我将选定的投资分配给工厂,但是在Step1 View,a a。

中没有任何更改反映

查看显示投资:

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

查看注册的步骤

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"

然后它正确显示值。

i只能怀疑newInvestmentFactoryupdate方法代码。它正在将investment对象重新分配到新的investment对象,例如this.investment = investment。通过该行,创建新的investment对象,而旧的investment则将引用释放。为了使investment对象在Update方法中不创建新变量,可以使用angular.extend/angular.merge方法。此方法不会创建对象的新引用,但可以确保所有对象属性都已更新。

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

在您的步骤控制器中

$scope.Investment = newInvestmentFactory.investment;

只是$示波器变量的一次分配,这不是两种绑定,因此,即使NewInvestmentFactory的值也不会更新范围。您可以做的是观看工厂变量newInvestmentFactory.Investment和"更改"手动更新范围。

希望这有帮助

最新更新