Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass $scope to angularjs 1.5 component/directive

I am trying to use the new .component() method in angular 1.5. Currently I have found little info on how to use it. The angular docs dont mention it really either.

I am trying to pass the scope or an object from the scope to the .component to be used in the template portion of the component but the only two parameters I can pass are $element and $attrs. I have tried passing the object through an attribute in the html but all I got was the string of the objects name.

I have tried setting it to be represented as a variable in these ways

my-attr="item.myVal"
my-attr="{item.myVal}"
my-attr="{{item.myVal}}"

each time I still get the string literal and not the value of the variable. How can I set it to be treated as a variable?

I have tried capturing the data via the new bindings: {} but my template:{} didnt have access to the variables then.

Here is my component as it is now:

export var ItemListAction = {
    controller: 'PanelCtrl as itemCtrl',
    isolate: false,
    template: ($element: any, $attrs: any): any=> {
        var myVal: any = $attrs.myAttr; // returns "item.myVal"
        var listAction: string = compileListAction();
        return listAction;
    }
};

Here is my component in HTML

<panel-item-list-action my-attr="item.myVal"></panel-item-list-action>

This is the angular module declaration for the component:angular.module('Panel', []).component('panelItemListAction', ItemListAction)

like image 370
appthat Avatar asked Jan 12 '16 23:01

appthat


1 Answers

Templates don't need $scope. Template functions return HTML. You can inject $scope in the controller as always.

This is what the AngularJS Blog says about components:

module.component

We have created a more simplistic way of registering component directives. In essence, components are special kinds of directives, which are bound to a custom element (something like <my-widget></my-widget>), with an associated template and some bindings. Now, by using the .component() method in AngularJS 1.5, you can create a reusable component with very few lines of code:

var myApp = angular.module("MyApplication", [])
myApp.component("my-widget", {
  templateUrl: "my-widget.html",
  controller: "MyWidgetController",
  bindings: {
    title: "="
  }
});

To learn more about the AngularJS 1.5 component method please read Todd Motto's article: http://toddmotto.com/exploring-the-angular-1-5-component-method/

-- http://angularjs.blogspot.com/2015/11/angularjs-15-beta2-and-14-releases.html

like image 187
georgeawg Avatar answered Nov 15 '22 19:11

georgeawg