Search code examples
javascriptangularjscomponentsangularjs-components

Get data from controller to Component AngularJs


I have a problem. I create a component in AngularJs and I want to pass data from controller to Component.

Data comes to template component, but in the controller on component is undefined!

This is my code.

The controller

angular.module('testModule')
.controller('testController', ['$scope',
    function($scope){
        var vm = this;
        vm.name = "John";
    }
]);

The component. Here in the console.log(vm.name) its undefined! This is my problem.

angular.module('testModule')
    .component('testComponent', {
        bindings: {
            "name": '='
        },
        controllerAs: 'ctrl',
        controller: ['$scope', function ($scope) {

            var vm = this;
            console.log(vm);              
            console.log(vm.name);
        }],
        template: "<h2>Hi {{ctrl.name}}</h2>",
    });

HTML

<html ng-app="testModule">
<head>
    <title>Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
    <script src="app.module.js"></script>
    <script src="testController.js"></script>
    <script src="testComponent.js"></script>
</head>
<body>
<div ng-controller="testController as ctrl">
    <test-component name="ctrl.name"></test-component>
</div>
</body>
</html>

Here is the Plunker

Any idea? Thanks!


Solution

  • You should be hooking up over $onInit method to see what component bindings has.

    vm.$onInit = function(){
        console.log(vm.name);
    }
    

    The things which you were trying to do was totally doable till angular 1.5.X, but since AngularJS 1.6+ version they disabled prepopulating context of controller by introducing preAssignBindingsEnabled over $compileProvider. By default it is set to false. If you really want to see this working you could try to set the flag by below code(but I'd not recommend to use this). The main reason behind introducing this change is to make Angular and AngularJS API to look similar by design & architecture, eventually it will make one step closer to migration to Angular.

    .config(function($compileProvider){
      $compileProvider.preAssignBindingsEnabled(true);
    })
    

    Plunker