AngularJS 1.5、组件属性未恢复

AngularJS 1.5, attributes in component isn t recovered

我知道这个 post Angular 1.5 component attribute presence 应该可以回答我的问题,但是我按照他们的方式做了所有事情,但我仍然无法恢复我的数据!如果你知道为什么.. :)

分量:

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>

模板已正确加载,但在我的控制台中,我得到的只是一个可怕的 "undefined"。

谢谢

我在您的代码中遇到的第一个问题是您在模板中使用的绑定名称,您必须将其用作 id-op="33" 而不是 idOp="33"

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

此外,在组件完全初始化之前,您将看不到绑定 属性。因此,您必须使用 $onInit 生命周期挂钩。

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

我制作了一个小应用程序,其中包含一个基于您的代码的组件,修复了我在其中发现的错误。

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>

参考资料

Understanding Components

Creating Custom Directives