javascript - 如何使用组件将值传递给 Controller ​​?

标签 javascript angularjs

我正在尝试通过我的组件将值传递给我的 Controller ,但我仍然收到此未定义的消息。我错过了什么吗?

myhtml.html

<my-component item="value1"></my-component>
<my-component item="value2"></my-component>
<my-component item="value3"></my-component>

mycomponent.js

angular
    .module('mycomponent.component', [
        'mycomponent.controller'
    ])
    .component('myComponent', {
        templateUrl: 'components/mycomp/mycomp.component.html',
        controller: 'ComponentController',
        controllerAs: 'componentVM',
        replace: true,
        bindings: {
            item: '='
        }
    });

mycontroller.js

angular
    .module('mycomponent.controller', [])
    .controller('ComponentController', ComponentController);

    ComponentController.$inject = [];

    function ComponentController() {
        var vm = this;
        console.log('item value> ' + vm.item); // This is got undefined :(
    }

最佳答案

正如 @mhodges 的评论中所建议的,把你所有的逻辑 里面$onInit钩。 $onInit当所有绑定(bind)都初始化时,作为组件生命周期的一部分触发。

var self = this;
self.$onInit = function(){
  console.log('item value> ' + self.item);
}

回到你的代码,如果 value1是一个原始类型,您应该使用单一方式绑定(bind) @ (原始类型不能使用双向绑定(bind),因为它们不是引用)

bindings: {
  item: '@'
}

<my-component item="value1"></my-component>

item 的场景中是一个对象,要将组件与外部环境解耦,最好使用单向绑定(bind) < ,

bindings: {
  item: '<'
}

这甚至会遵循 Angular > 1.5 的准则,旨在基于组件的架构。

来自 Angular 1.5 文档:

Inputs should be using < and @ bindings. The < symbol denotes one-way bindings which are available since 1.5. The difference to = is that the bound properties in the component scope are not watched, which means if you assign a new value to the property in the component scope, it will not update the parent scope

https://docs.angularjs.org/guide/component

关于javascript - 如何使用组件将值传递给 Controller ​​?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44641688/

相关文章:

javascript - 以全屏模式运行网站

javascript - 尝试访问 json 数组中的嵌套项目

javascript - Angular 文档 Controller

javascript - 如何在取消选择芯片 : AngularJS 时弹出数组的值

javascript - 使用 ES 模块运行 pm2

javascript - 清除 PHP 和 JS 中的历史记录和引用数据?

javascript - 在 iPad 和 iPhone 上滚动 iframe

javascript - AngularJS:单选按钮不适用于 Bootstrap 3

javascript - 按值更改字体颜色

javascript - <select> getter-setter 以字符串形式接收对象参数