1

我有以下代码,我希望variable在页面中显示属性的内容。我阅读了几篇文章并试图找出我做错了什么,但找不到错误。这是代码:

namespace testWeb.about {
    class AboutComponent implements ng.IComponentOptions {
        templateUrl = "scripts/components/about/about.html";
        controller = AboutController;
        bindings: any;

        constructor() {
            this.bindings = {
                awesomeThings : '<',
                property : '<'
            };
        }
    }

    interface IAboutController {
        awesomeThings: Array<string>;
        property: string;
    }

    export class AboutController implements IAboutController, ng.IComponentController {
        awesomeThings: Array<string>;
        property: string;

        constructor() {
            this.awesomeThings = [
                "one",
                "two",
                "three"
            ];
            this.property = "123";
        }
    }
    angular.module("test_web")
        .component("about", new AboutComponent())
        .config(($stateProvider) => {
            "ngInject";
            $stateProvider
                .state("about", {
                    url: "/about",
                    template: `<about></about>`
                });
        });
}

是否<span ng-repeat="dd in $ctrl.awesomeThings">{{dd}}</span>也不会<span class="as">{{$ctrl.property}}</span>显示。

<span ng-repeat="dd in $ctrl.awesomeThings">{{dd}}</span>
<span class="as">{{$ctrl.property}}</span>
<p>123</p>
4

1 回答 1

1

此行为是由Angular 1.6 中禁用的预分配绑定引起的。

在 1.5 中,this.property = "123"会覆盖初始绑定值,即使它已提供。

在 1.6 中,绑定是在构造函数调用之后分配的。如果未提供绑定的值,property则分配给undefined

为了防止这种情况并提供所需的行为绑定应标记为可选:

this.bindings = {
    awesomeThings : '<?',
    property : '<?'
};

或者,可以在$onInit钩子中分配初始值,这允许忽略绑定中的虚假初始值,例如:

constructor() {}

$onInit() {
    this.awesomeThings = this.awesomeThings || [
        "one",
        "two",
        "three"
    ];
    this.property = this.property || "123";
}
于 2017-04-18T14:46:07.070 回答