【问题标题】:AngularJS component bindings not passing objectAngularJS组件绑定不传递对象
【发布时间】:2018-01-31 02:39:14
【问题描述】:

接收错误无法读取 PollListCtrl.runQuery 中未定义的属性“类型”。 我不确定为什么这是未定义的。我已经在控制台记录了 profile-polls.controller.js,其中创建了 listConfig 以确保这里有一个对象。回应是

{type: "all", filters: {pollsCreated: Array(3)}}

但是当我尝试将它传递给 profile-polls.html 中的 poll-list 组件时,它会出现未定义。以下是相关文件的要点。谁能告诉我为什么这没有正确通过?

https://gist.github.com/RawleJuglal/fa668a60e88b6f7a95b456858cf20597

【问题讨论】:

  • 如果在第 57 行下断点,queryConfig 是否未定义?
  • 我的调试技能不强,所以我不确定如何在 chrome 中查看断点,但在此之前我做了一个 queryConfig 的控制台日志。_Polls.query 但它没有得到那个远的。我假设是因为它在第 41 行抛出错误。

标签: angularjs angular-components


【解决方案1】:

我认为你需要为你的组件定义观察者。在开始时listConfig 是未定义的,并且只有在一些延迟(下一个摘要周期)之后它才会获得价值。所以我们创建观察者并在if语句之后取消它。

app.component('pollList', {
  bindings: {
    listConfig: '='
  },
  templateUrl: 'poll-list.html',
  controllerAs: 'vm',
  controller: PollListCtrl
});

function PollListCtrl($scope) {

    var vm = this;

    function run(){
      console.log(vm.listConfig);
    }


    var cancelWatch = $scope.$watch(function () {
        return vm.listConfig;
    },
    function (newVal, oldVal) {

        if (newVal !== undefined){
            run();
            cancelWatch();
        }
    });
}

Demo plunkr

【讨论】:

  • 抱歉尝试了这个但没有改变。我的理解也是,配置中的 controllerAs 会做同样的事情。不是这样吗?
【解决方案2】:
  • 永远不要在 angularjs 应用程序中使用 $scope。
  • 您可以使用 ngOnInit() 生命周期钩子来访问“绑定”值而不是构造函数。

    ngOnInit(){

    $ctrl.listConfig = { type: 'all' };

    $ctrl.limit = 5;

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 2017-08-19
    • 2018-03-03
    • 1970-01-01
    • 2017-05-22
    • 2021-02-22
    相关资源
    最近更新 更多