简体   繁体   中英

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. However, printing to the console gives me undefined in the following example and I'm not sure why.

index.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

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.

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.

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

Below is a working example.

It is because you are trying to access it too soon. There is a component lifecycle hook called $onInit . All bindings will be resolved in that function, so you can use that to access your name property.

Try to modify your controller to something like this:

controller: () => {

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

}

$onChanges runs before $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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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