Angular 1.5 Component: passing a function Angular 1.5 Component: passing a function angularjs angularjs

Angular 1.5 Component: passing a function


You can pass functions to components, but you must define the function arguments as object with the correct arguments names as its keys.example:

<post-list posts="blog.posts"           loading="blog.loadingPosts"           get-post-url="blog.getPostUrl(postId)"            is-user-authenticate="blog.user"></post-list>const PostList = { "bindings": {  "posts": "<",  "loading": "<",  "getPostUrl": "&", //Function getPostUrl  "isUserAuthenticate": "<" }, "template": `<post creation-date="{{post.creationDate}}"                      content="{{post.content}}"                      post-url="{{$ctrl.getPostUrl({postId:post.creationDate})}}">                </post>


If you want to call the function from inside a component and have it return a value then you need two-way binding:

"bindings": {  "posts": "<",  "loading": "<",  "getPostUrl": "=", // <-- two-way binding  "isUserAuthenticate": "<"},

However, this is probably not very good idea. Consider passing data to component rather than making component request data from outside. This will make much better isolated component.


To return a value to the binding function you must pass it as a object literal.
self.selected({id: '42', firstname: 'Douglas', lastname: 'Adams'});

angular.module('webapp').component('myComponent', {    templateUrl: 'myComponent.html',    bindings: {        selected: '&'    },    controller: function () {        var self = this;        self.someEvent= function(){            self.selected({id: '42', firstname: 'Douglas', lastname: 'Adams'});        };    }});

Afterwards you can access the object literal values by it's properties.
id, firstname, lastname.
You can also pass additional parameters to the function. (myVariable)

<div>    <span ng-init="myVariable='Universe'">    <my-component selected="myFunction(id, firstname, lastname, myVariable)"></my-component></div>$scope.myFunction = function(id, firstname, lastname, myVariable){    console.log(id, firstname, lastname, myVariable);    }