【问题标题】:Cannot bind to rootscope in Angular 1.5 component无法绑定到 Angular 1.5 组件中的 rootscope
【发布时间】:2017-03-06 19:04:56
【问题描述】:

我正在按照本指南消除旧版 Angular 1.5 应用程序的“范围汤”架构:http://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-components.html#replace-external-reference-with-bound-input

我正在尝试删除对$rootscope.taskui 的引用,因此我尝试向组件添加绑定。不幸的是,taskui 现在未定义。 “组件”是一个 Angular 1.5 组件(它只是一个普通的指令)。我做错了吗?

如果将“this.taskui”替换为“$rootscope.taskui”(正确注入),method 会很好地打印 taskui 对象。

export default {
   bindings: {
     taskui: '='
   },
   controller,
   templateUrl: "component.html"
 };

这是控制器代码:

class Controller {

   constructor() {

      this.method = () => console.log(this.taskui)
   }
}

【问题讨论】:

  • 您应该在使用该指令的地方显示 HTML 代码。如果您没有为 taskui 传递值,它将是未定义的。
  • @sunil D --- 当然它已经定义好了!我正在重构这个应用程序,所以当我调用 $rootscope.taskui 时它存在。请在投票前仔细阅读
  • 我没有投反对票 :) 我的观点仍然成立。使用指令时,您需要传入 taskui 的值。我不是说$rootscope.taskui 是未定义的......我是说在你的HTML 中,你没有在这里显示,你必须这样做:<my-directive taskui="someScopeVariable">。而且我猜测(已经有一段时间了)你不能在 HTML 中引用 $rootScope 所以你需要设置一个本地的 $scope 变量等于那个值。
  • @georgeawg 你还在看书吗? this.taskui 不起作用,即当您将 rootscope 替换为绑定时,它会停止工作。
  • 如果你有嵌套组件,你需要在嵌套的每一层绑定变量。组件使用不会从原型继承父范围的隔离范围。

标签: angularjs angularjs-scope ecmascript-6 angularjs-rootscope angular-components


【解决方案1】:

问题是对 angularjs 范围的误解。当使用隔离作用域时,仅仅绑定一个变量是不够的。您还必须将值作为属性传递。在此处查看解决方案#3:https://stackoverflow.com/a/17900556/555493

代码(使用原始示例)应该是:

// component
export default {
  bindings: {
    taskui: '='
  },
  controller,
  templateUrl: "component.html"
 };

// parent template
<component taskui="taskui"></component>

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 2017-03-21
    • 2016-09-12
    • 2017-01-24
    • 2016-07-25
    • 2017-05-10
    • 2016-07-03
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多