简体   繁体   English

Angular 1.5 组件未将变量传递给组件

[英]Angular 1.5 components not getting variable passed to component

I'm new to .component() in Angular 1.5+ and I'm trying to create data in the top level app controller, and pass it to a child component.我是 Angular 1.5+ 中的 .component() 新手,我正在尝试在顶级应用程序控制器中创建数据,并将其传递给子组件。 However, printing to the console gives me undefined in the following example and I'm not sure why.但是,在下面的示例中,打印到控制台给了我 undefined ,我不知道为什么。

index.html索引.html

<!DOCTYPE html>
<html>
<head>
    <script src="Scripts/angular.js"></script>
    <script src="app.js"></script>
    <title></title>
    <meta charset="utf-8" />
</head>
<body ng-app="myApp" ng-controller="myController as vm">
    <app name="vm.myName"></app>
</body>
</html>

app.js应用程序.js

var app = angular.module("myApp", []);

app.controller("myController", ['$scope', function ($scope) {
    console.log("myController!");

   $scope.myName = "Rick";
}]);

app.component("app", {
    template: '<h1>Hello World</h1>',
    bindings: {
        name: '='
    },
    controller: function () {
        console.log(this.name); <-- prints undefined
    }
});

The problem is that in the controller you are using the $scope to define the variable that is getting passed into the component but, in the controller block of the HTML you are using the this syntax for passing the variable into the component.问题是,在控制器中,您使用$scope来定义传递到组件中的变量,但是,在 HTML 的控制器块中,您使用this语法将变量传递到组件中。

So the line with the problem is.所以问题所在。

app.controller("myController", ['$scope', function ($scope) {
    console.log("myController!");
   $scope.myName = "Rick";
}]);

This is a standard scope syntax, but since we are using this syntax we need it to be.这是一个标准的scope语法,但由于我们正在使用this语法,因此我们需要它。

app.controller("myController", ['$scope', function ($scope) {
    console.log("myController!");
    this.myName = "Rick";
}]);

Below is a working example.下面是一个工作示例。

JSFiddle Demo JSFiddle 演示

It is because you are trying to access it too soon.这是因为您试图过早地访问它。 There is a component lifecycle hook called $onInit .有一个名为$onInit的组件生命周期钩子。 All bindings will be resolved in that function, so you can use that to access your name property.所有绑定都将在该函数中解析,因此您可以使用它来访问您的name属性。

Try to modify your controller to something like this:尝试将您的控制器修改为如下所示:

controller: () => {

    this.$onInit = () => {
        console.log(this.name);
    }

}

$onChanges runs before $onInit . $onChanges$onInit之前运行。 You can simply check when your value is passed to your component using this block of code:您可以使用以下代码块简单地检查您的值何时传递给您的组件:

this.$onChanges = (changesObj) => {
    if(changesObj.name && changesObj.name.currentValue) {
        console.log(this.name);
    }
}

You might want to take further look at angularjs 1.5+ components' documentation您可能想进一步查看 angularjs 1.5+ 组件的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM