AngularJS 1.5,组件中的属性未恢复

时间:2017-08-24 17:10:23

标签: angularjs angularjs-components

我知道这篇文章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>

模板是正确加载的,但在我的控制台中,我得到的只是一个可怕的&#34;未定义&#34;。

THX

1 个答案:

答案 0 :(得分:1)

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

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

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

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

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

&#13;
&#13;
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);
        };
      }
    ]
  });
&#13;
<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>
&#13;
&#13;
&#13;

参考文献

Understanding Components

Creating Custom Directives

相关问题