Search code examples
angularjsangularjs-components

AngularJS 1.5, attributes in component isn t recovered


I know this post Angular 1.5 component attribute presence should answer my question but I did everything like they did and I still can t recovered my data! If you have any idea why.. :)

Component:

component('ficheOperation', {
    templateUrl : 'operations/creerOperation.template.html',
    bindings : {
      idOp : '<'
    },
    controller : ['$scope', '$routeParams', '$location',
      function ficheOperationController($scope, $routeParams, $location){
        var self = this;
        console.log(self.idOp);
    }]
})

HTML :

<fiche-operation idOp="33"></fiche-operation>

the template is rightfully loaded but in my console all I get is a horrific "undefined".

Thx


Solution

  • First problem I encountered in your code was the binding name you used in the template, you have to use it as id-op="33" instead of idOp="33".

    <fiche-operation id-op="33"></fiche-operation>
    

    Also, you won't be able to see the binding property before the component has gotten fully initialized. Therefore, you have to make use of the $onInit life cycle hook.

    this.$onInit = function() {
        console.log(self.idOp);
    };
    

    I made a small app with a component based on your code which fix the errors I found in it.

    angular
      .module('myApp', [])
      .component('ficheOperation', {
        template: '{{ $ctrl.idOp }}',
        bindings: {
          idOp: '<'
        },
        controller: ['$scope', '$location',
          function ficheOperationController($scope, $location) {
            var self = this;
    
            self.$onInit = function() {
              console.log(self.idOp);
            };
          }
        ]
      });
    <div ng-app="myApp">
      <fiche-operation id-op="33"></fiche-operation>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>

    Refs

    Understanding Components

    Creating Custom Directives