angularjs - Angular 选择绑定(bind)破坏模型中的引用

标签 angularjs typescript

Angular 版本为 1.4.7。

所讨论的模型包含两个对象,“systems”、一个数组和“selectedSystem”。我想要的是让 selectedSystem 引用系统中的对象之一。这是页面加载时的情况,一切都按预期工作,但是当我从第一个下拉列表中进行选择时,selectedSystem 似乎变成了副本而不是对系统中原始对象的引用。因此,对第二个下拉列表的更改不再反射(reflect)在系统中。

<!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>

typescript 代码:

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

这是怎么回事,有什么方法可以通过 Angular 模型绑定(bind)获得我想要的行为吗?

最佳答案

来自 future 的问候。

和你有类似的问题,而且因为这已经超过一年了,我想我会做一些挖掘。这似乎是设计使然,即使在 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

关于angularjs - Angular 选择绑定(bind)破坏模型中的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32895461/

相关文章:

javascript - 来自 JSON 数组的动态菜单

reactjs - 在 Typescript 中,如果设置了另一个可选属性,如何使属性成为必需?

javascript - 当我使用 jest(ts-jest async/await test) 时,WebStorm 提示我 TS 错误 (TS2705)

javascript - 在使用 typescript 的 Jasmine 测试中注入(inject) $http 失败

javascript - 在 Angular 中将 <select> 与嵌套对象一起使用

angularjs - 构建 AngularJS 包后,如何使用 NodeJS 作为后端请求服务器来部署 AngularJS

angular - 使用 json 响应生成动态列表

node.js - 如何在 Ionic 2 中为在本地主机中运行的 Node 服务器发送发布请求?

javascript - AngularJS 列表之间的拖放在 1.2 中中断

angularjs - 303 重定向不适用于 Angular HTTP POST