2016-04-27 120 views
9

是否有可能將一個函數傳遞給一個組件,並在組件內傳遞該函數來傳遞一個參數?Angular 1.5組件:傳遞一個函數

實施例:

帖子

<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)}}"我要調用傳遞參數的功能,這個功能是返回一個字符串

交分量(未PostList)的postUrl是一個字符串屬性@

但是...不工作!

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

是否有可能做到這一點?如何?

非常感謝!

+0

你不需要'{{}}'爲'&'結合 - 看到文檔的這一部分對於如何實現你希望做一個很好的例子: https://docs.angularjs.org/guide/component#component-based-application-architecture –

+0

但是這個函數的返回值是一個字符串......'post-url'是一個字符串。我想調用返回這個字符串的函數 –

+0

我現在改變了...但是現在出現這個錯誤:'不能使用'在'操作符來搜索'博客'' –

回答

5

如果你想從一個組件內調用函數,並讓它返回一個值,那麼你需要雙向綁定:

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

然而,這可能不是個好主意。考慮將數據傳遞到組件,而不是從外部發送組件請求數據。這將使得更好的孤立組件。

+0

謝謝,現在正在工作! –

9

您可以將函數傳遞給組件,但您必須將函數參數定義爲具有正確參數名稱作爲其鍵的對象。 例如:

<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> 
+0

真棒,謝謝 – 1Canuck16

+2

這應該是真正的接受解決方案,因爲它是正確的功能綁定。謝謝你的提示。我不知道內部組件必須將param作爲命名對象傳回。 – gilm0079