传递的参数未从{{variable}}转换

时间:2016-02-17 08:37:36

标签: angularjs

我有一堆用于不同路线的控制器和一个工厂来存储所有控制器所需的一些数据。

.factory( 'global', function() {
    return {
        posts: null,
        selected_post: null,
        selectPost: function( post_id ) {
            console.log( 'test from factory: selecting post by id', post_id );
        }
    };
})

控制器之一

.controller('postsCtrl', ['$scope', '$http', 'global', '$location', function($scope, $http, GLOBAL, $location ) {
    // ...  
    $scope.editPost = function( post_id ) {
        console.log( 'test from editPost', post_id );
        GLOBAL.selectPost( post_id );
        $location.path( '/posts/edit' );
    };
    // ...
}])

..从ng-repeat内的模板调用函数,将帖子id传递给工厂,就像这样

tr(ng-repeat='p in posts')
    td
        a.btn(ng-click="editPost('{{p.id}}')") Edit post

这正如我所期望的调用函数一样,将id之类的字符串传递给工厂的selectPost函数。

如果我右键单击按钮打开检查器,我可以看到标签实际上看起来像这样(id是一个字符串,正如我预期的那样)

<a href="" ng-click="editPost('56c1b7b80712d1f307fbd842')" class="btn">edit</a>

唯一的问题是在控制台中我得到的消息如下:

test from editPost {{p.id}}
test from factory: selecting post by id {{p.id}}

那么为什么尽管检查员显示应该使用id的字符串参数调用函数,但我看到内部函数{{p.id}}

2 个答案:

答案 0 :(得分:1)

你可以将它交给函数而不将其转换为类似的字符串,你将在函数中将id作为参数:

a.btn(ng-click="editPost(p.id)") Edit post

答案 1 :(得分:0)

  

a.btn(ng-click="editPost('{{p.id}}')") Edit post

通过编写,您将参数设置为字符串,其中包含“{{p.id}}”。

将其更改为:

a.btn(ng-click="editPost({{p.id}})") Edit post

或者只是:

a.btn(ng-click="editPost(p.id)") Edit post
相关问题