【问题标题】:Angular 1.5+ Nested Component binding on the value returned by promiseAngular 1.5+嵌套组件绑定到promise返回的值
【发布时间】:2017-05-18 14:10:43
【问题描述】:

我目前正在学习 AngularJS 组件。我想在父组件和子组件之间绑定一个值,知道父组件中的值是由 RESTful 服务返回的:

parent.template.html

<h3>{{$ctrl.hero.name}}</h3>
<child hero="$ctrl.hero"></child>

parent.component.js

 angular.module('myApp')
    .component('parent', {
        templateUrl:'parent/parent.template.html',
        controller: ['MyService','$routeParams', parentController]
    });

function parentController(MyService, $routeParams) {
    var self = this;
    MyService.get({ heroId: $routeParams.heroId })
        .$promise
            .then(function (data) {
                self.hero = data; 
                console.log("self.hero:" + self.hero); //this will log the hero correctly.
            });
    console.log("self.hero.name"+ self.hero.name) // this will log "undefined"
};

child.template.html

<div>{{$ctrl.hero.name}}</div>

child.component.js

    angular.module('myApp')
    .component('child', {
        templateUrl:'child/child.template.html',
        controller: childController,
        bingdings: {
            hero:'='
        },
        transclude:true
    });

function childController() {
    var self = this;
    console.log("child hero: " + self.hero); // this will output "undefined"
};

我认为子组件无法从父组件中获取“英雄”,因为“英雄”是由 $promise 返回的。

你有想法如何绑定这样的值吗?

提前感谢您的帮助!

问候, 蕾欧娜

【问题讨论】:

  • @raina77ow 我会给你正确的答案!....这是由于“绑定”的拼写错误...谢谢...
  • 对于以后会看这篇文章的用户:我们可以像往常一样绑定 $promise 返回的值。如果不能,请仔细检查拼写...

标签: angularjs


【解决方案1】:

在这种情况下,这是一个简单的错字 - 应该是 bindings 而不是 bingdings。作为旁注,在这种特殊情况下,使用所谓的one-way binding 是有益的,自 1.5 版起可用:

.component('child', {
  templateUrl:'child/child.template.html',
  controller: childController,
  bindings: {
    hero: '<'
  },
  transclude:true
});

...因为子组件中的更改永远不应影响父范围,并且不会被跟踪。这很好——无论是内存还是速度。

【讨论】:

    猜你喜欢
    • 2016-07-03
    • 2016-12-24
    • 1970-01-01
    • 2014-02-21
    • 2017-03-18
    • 2016-09-10
    • 2016-12-15
    • 1970-01-01
    • 2018-08-27
    相关资源
    最近更新 更多