角度选择绑定打破模型中的引用

时间:2015-10-01 19:33:14

标签: angularjs typescript

Angular版本是1.4.7。

有问题的模型包含两个对象,'系统',数组和'selectedSystem'。我想要的是selectedSystem引用系统中的一个对象。这是页面加载时的情况,一切都按预期工作,但是当我从第一个下拉列表中进行选择时,selectedSystem似乎变成了一个副本,而不是对系统中原始对象的引用。因此,第二次下拉的更改不再反映在系统中。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Hello</title>
</head>
<body ng-app="testApp">
    Hi There!
    <div ng-controller="TestAppSummaryCtrl">
        <input type="button" value="Add Query" ng-click="addQuery()"/>
        <select ng-model="state.selectedSystem" ng-options="system.description for system in state.systems track by system.systemId" ></select>
        <select ng-model="state.selectedSystem.currentEnvironment" ng-options="environment.description for environment in state.selectedSystem.environments track by environment.environmentId"></select>
        Selected System: {{state.selectedSystem.systemId}}

        <div ng-repeat="item in state.systems">
            System: {{item.description}}
            Current Environment: {{item.currentEnvironment.description}}
        </div>

        <div ng-repeat="item in state.selectedSystem.categories">
            Cateogry:
            {{item.categoryId}}
            {{item.description}}
            <br />
            Queries:
            <div ng-repeat="query in item.queries">
                {{query.queryId}}
                {{query.latestStatus}}
            </div>
        </div>
    </div>
    <script src="../Scripts/angular.js"></script>
    <script src="../Scripts/angular-route.js"></script>
    <script src="src/test.js"></script>
</body>
</html>

打字稿代码:

/// <reference path="../../scripts/typings/angularjs/angular.d.ts" />
/// <reference path="../../scripts/typings/angularjs/angular-route.d.ts" />

module TestApp {
    export class Config {
        constructor($routeProvider: ng.route.IRouteProvider) {
            $routeProvider.when("/test", {
                templateUrl: "StaticContent/StaticTest.html",
                controller: "TestAppCtrl"
            });
        }
    }

    Config.$inject = ['$routeProvider'];

    export class SummaryService {
        private summaryApiPath: string;
        private httpService: ng.IHttpService;
        private qService: ng.IQService;
        private systems: Array<Extensions.SystemSummary>;

        constructor($http: ng.IHttpService, $q: ng.IQService) {
            this.summaryApiPath = "../api/systemList";
            this.httpService = $http;
            this.qService = $q;
        }

        getSystems(): ng.IPromise<any> {
            if (this.systems != undefined) {
                return this.qService.when(this.systems);
            }
            var deferred = this.qService.defer();
            this.httpService.get(this.summaryApiPath).then((result: any) => {
                deferred.resolve(result.data);
            }), error => {
                deferred.reject(error);
            }
            return deferred.promise;
        }

        public static serviceFactory($http: ng.IHttpService, $q: ng.IQService): SummaryService {
            return new SummaryService($http, $q);
        }
    }

    export class TestAppSummaryCtrl {
        private $scope: Extensions.ISummaryScope
        private summaryService: SummaryService;

        private init(): void {
            var local = this.$scope;
            this.summaryService.getSystems().then(data => {
                local.state.systems = <Array<Extensions.SystemSummary>>data;
                local.state.selectedSystem = local.state.systems.length == 0 ? undefined : local.state.systems[0];
            });
            local.updateCurrentEnvironment = envId => local.state.selectedSystem.currentEnvironment = local.state.selectedSystem.environments[envId];
        }

        constructor($scope: Extensions.ISummaryScope, summaryService: SummaryService) {
            this.$scope = $scope;
            this.$scope.state = new Extensions.SummaryCtrlUIState();
            this.summaryService = summaryService;
            this.init();
        }
    }

    TestAppSummaryCtrl.$inject = ['$scope', 'summaryService'];

    var app = angular.module('testApp', ['ngRoute']);
    app.config(Config);
    app.factory('summaryService', ['$http', '$q', SummaryService.serviceFactory]);
    app.controller('TestAppSummaryCtrl', TestAppSummaryCtrl);
}

module Extensions {
    export class CategorySummary {
        categoryId: number;
        description: number;
        queries: Array<JobItemSummary>;
    }

    export class JobItemSummary {
        queryId: number;
        lastJobId: number;
        lastCompletedDate: string;
        latestStatus: string;
        latestResultsCount: number;
        latestResultsSummary: string;
        expectedResult: number;
    }

    export class EnvironmentSummary {
        environmentId: number;
        description: string;
    }

    export class SystemSummary {
        systemId: number;
        description: string;
        environments: Array<EnvironmentSummary>;
        currentEnvironment: EnvironmentSummary;
        categories: Array<CategorySummary>;
    }

    export class SummaryCtrlUIState {
        selectedSystem: Extensions.SystemSummary;
        systems: Array<Extensions.SystemSummary>;
    }

    export interface ISummaryScope extends ng.IScope {

        state: SummaryCtrlUIState;
        updateCurrentEnvironment(envId: number): void;
        addQuery(): void; 
    }
}

发生了什么,是否有某种方法可以通过角度模型绑定获得我想要的行为?

1 个答案:

答案 0 :(得分:1)

来自未来的问候。

和你有类似的问题,因为这已经超过一年了,我想我会做一些挖掘。这似乎是设计,即使在v1.6。 Lines 399-403 of ngOptions has this interesting tidbit

        getViewValueFromOption: function(option) {
            // If the viewValue could be an object that may be mutated by the application,
            // we need to make a copy and not return the reference to the value on the option.
            return trackBy ? copy(option.viewValue) : option.viewValue;
        }

所以是的,track by正在为ngModel复制价值。目前我认为唯一的办法是编写自己的逻辑来跟踪选择和/或将更改发送回原始数组。

编辑:我在angular.js github repo上打开了一个问题:https://github.com/angular/angular.js/issues/15980