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

时间:2017-04-30 09:11:47

标签: javascript angularjs

我有单一视图显示投资+另外两个是用于注册新投资的模式,当用户点击并添加' (两个模态因为两个注册步骤)。我创建了工厂,它在步骤1中使用,然后在步骤2中用于保存有关投资的信息 - 当您在步骤1和步骤2之间来回切换时,它会起作用。
问题是,在显示投资的第一个视图中,我有图标"编辑"在其处理程序(编辑方法)中,我将选定的投资分配给工厂,但步骤1视图中没有反映出任何变化,唉。

查看显示投资:

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"

然后它正确显示值。

2 个答案:

答案 0 :(得分:1)

我只能怀疑newInvestmentFactory的{​​{1}}方法代码。它会将update对象重新分配给investment之类的新investment对象。通过该行,创建了新的this.investment = investment对象,旧的investment松散了引用。要使investment对象不在update方法中创建新变量,可以使用investment / angular.extend方法。此方法不会创建对象的新引用,但会确保所有对象属性都已更新。

angular.merge

答案 1 :(得分:0)

在步骤控制器中

$scope.Investment = newInvestmentFactory.investment;

只是一次分配给$ scope变量,这不是双向绑定,所以即使newInvestmentFactory.investment的值更改范围也不会更新。您可以做的是观察工厂变量newInvestmentFactory.investment并在更改时手动更新范围。

希望这有帮助