Ara*_*oca 11 javascript components angularjs
是否可以将函数传递给组件并在传递参数的组件内调用此函数?
例:
帖子列表
<post-list posts="blog.posts"
loading="blog.loadingPosts"
get-post-url="blog.getPostUrl"
is-user-authenticate="blog.user">
</post-list>
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)
帖子列表:组件
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);
Run Code Online (Sandbox Code Playgroud)
在这一行:
post-url="{{$ctrl.getPostUrl(post.creationDate)}}"我想调用传递参数的函数,这个函数返回一个字符串.
在post组件(不是PostList)中,postUrl是一个字符串属性@.
但是......不工作!
angular.js:13550错误:[$ interpolate:interr]无法插值:{{$ ctrl.getPostUrl(post.creationDate)}} TypeError:无法使用'in'运算符在1459329888892中搜索'blog' 错误链接
有可能吗?如何?
非常感谢!
Dor*_*ron 21
您可以将函数传递给组件,但必须将函数参数定义为对象,并将正确的参数名称作为其键.例:
<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>
Run Code Online (Sandbox Code Playgroud)
如果要从组件内部调用该函数并让它返回一个值,那么您需要双向绑定:
"bindings": {
"posts": "<",
"loading": "<",
"getPostUrl": "=", // <-- two-way binding
"isUserAuthenticate": "<"
},
Run Code Online (Sandbox Code Playgroud)
但是,这可能不是一个好主意.考虑将数据传递给组件,而不是从外部发出组件请求数据.这将使更好的隔离组件.
| 归档时间: |
|
| 查看次数: |
15054 次 |
| 最近记录: |