Angular 1.5 Component:传递一个函数 [英] Angular 1.5 Component: passing a function

查看:78
本文介绍了Angular 1.5 Component:传递一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将函数传递给组件并在传递参数的组件内调用此函数?

Is it possible to passing a function to a component and call this function inside the component passing a parameter?

示例:

帖子列表

<post-list posts="blog.posts"
           loading="blog.loadingPosts"
           get-post-url="blog.getPostUrl" 
           is-user-authenticate="blog.user">
</post-list>

getPostUrl 是一个函数(容器控制器内的):

getPostUrl is a function (inside the container controller):

const getPostUrl = (postId) => {
    const protocol = $location.protocol();
    const host = $location.host();
    const port = $location.port();

    return protocol + "://" + host + "" + (port !== 80 ? ":" + port : "") + "/blog/post/" + postId;
};

帖子列表:组件

const PostList = {
  "bindings": {
    "posts": "<",
    "loading": "<",
    "getPostUrl": "&", //Function getPostUrl
    "isUserAuthenticate": "<"
  },
  "template": `<div>
                <div class="col-md-9 text-center" data-ng-if="$ctrl.loading">
                  <i class="fa fa-spinner fa-spin fa-2x"></i>
                </div>

                <div class="col-md-9 posts" data-ng-if="!$ctrl.loading">
                  <div data-ng-repeat="post in $ctrl.posts">
                    <post creation-date="{{post.creationDate}}"
                          content="{{post.content}}"
                          post-url="{{$ctrl.getPostUrl(post.creationDate)}}"
                          is-user-authenticate="$ctrl.user">
                    </post>
                  </div>
                </div>
              </div>`,
   "transclude": false
};

 angular
  .module("blog")
  .component("postList", PostList);

在此行中:

post-url ={{$ ctrl.getPostUrl(post.creationDate)}}我想调用传递参数的函数,此函数返回字符串

post-url="{{$ctrl.getPostUrl(post.creationDate)}}" I want to call the function passing a parameter and this function is returning a string.

发布组件(不是PostList)中,postUrl是一个字符串属性 @

In post component (not PostList) the postUrl is a string attribute @.

但是......不工作!

But... Is not working!


angular.js:13550错误:[$ interpolate:interr]无法插值:{{$ ctrl.getPostUrl(post.creationDate)}}
TypeError:不能使用'in'运算符来在1459329888892搜索'博客'
错误链接

是否可以这样做?怎么样?

非常感谢你!

推荐答案

如果你想从一个组件内部调用该函数并让它返回一个值,那么你需要双向绑定:

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.

这篇关于Angular 1.5 Component:传递一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆