Angular 1.5 Component: passing a function(Angular 1.5 组件:传递函数)
问题描述
是否可以将函数传递给组件并在传递参数的组件内部调用此函数?
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 是一个函数(在容器控制器内):
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.
在 post 组件(不是 PostList)中,postUrl 是一个字符串属性 @
.
In post component (not PostList) the postUrl is a string attribute @
.
但是...不起作用!
angular.js:13550 错误:[$interpolate:interr] 无法插值:{{$ctrl.getPostUrl(post.creationDate)}}TypeError:无法使用in"运算符在 1459329888892 中搜索博客"错误链接
angular.js:13550 Error: [$interpolate:interr] Can't interpolate: {{$ctrl.getPostUrl(post.creationDate)}} TypeError: Cannot use 'in' operator to search for 'blog' in 1459329888892 Error Link
有可能吗?以及如何?
非常感谢!
推荐答案
如果你想从组件内部调用函数并让它返回一个值,那么你需要双向绑定:
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 组件:传递函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Angular 1.5 组件:传递函数
基础教程推荐
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01