U Avalos U Avalos - 1 month ago 41
AngularJS Question

Cannot bind to rootscope in Angular 1.5 component

I'm in the process of eliminating the "scope soup" architecture of a legacy Angular 1.5 app following this guide: http://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-components.html#replace-external-reference-with-bound-input

I'm trying to remove the reference to

$rootscope.taskui
, so I tried to add a binding to the component. Unfortunately,
taskui
is now undefined. The "component" is an Angular 1.5 component (which is just a normal directive under the hood). Am I doing something wrong?

If you replace "this.taskui" with "$rootscope.taskui" (correctly injected),
method
prints the taskui object just fine.

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


Here's the controller code:

class Controller {

constructor() {

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

Answer

The problem was a misunderstanding of angularjs scope. When using isolated scope, it is not enough to just bind a variable. You must also pass the value as an attribute. See solution #3 here: http://stackoverflow.com/a/17900556/555493

The code (using the original example) should be:

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

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