AngularJs将模型属性绑定到复选框

时间:2016-03-16 11:00:54

标签: javascript angularjs checkbox mean-stack

我正在尝试为帖子创建分配一些标签。 我有一个Post模型,如下所示:

var mongoose = require('mongoose');

var PostsSchema = {
    title: String,
    content: String,
    postedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Users'
    },
    comments: [{
        text: String,
        postedBy: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Users'
        },

    }],

    tags: [String]

};

我正在尝试将一些复选框绑定到Post中的'tags'数组属性。

这就是我的帖子路由器的样子:

///* Create post */
postRouter.route('/').post(function (req, res) {

        mongoose.createConnection('localhost', 'CMS');
        console.log(req.body);

        var post = {
            title: req.body.title,
            content: req.body.content,
            tags: req.body.tags

        };

        if (typeof req.body.title === "undefined" || typeof req.body.content === "undefined")
        {
            res.json({message:"Error"});
        }else
        {
        var newPost = new Posts(post);
        newPost.save(function (err, post) {
            if (err) res.json({message:"Error"});
            res.json(post);
        });
        }

});

我的控制器如下:

$scope.createPost = function(post){
        postService.createPost(post);
        postService.getPosts()
            .then(modelPosts);
    }

我的观点如下:

div(ng-controller='postController') 
h2 Create Post
                    form
                        div.form-group
                            label(for='title') Title
                                input(type='text', class='form-control', id='title', name='title', placeholder='Title', ng-model='newpost.title', autofocus)
                        div.form-group
                            label(for='password') Content
                                input(type='text', class='form-control', id='content', name='content', placeholder='content', ng-model='newpost.content')
                    div(ng-controller='tagController')
                        h2 Tags
                        div( ng-model='Tags', ng-init='getTags()')
                            ul( ng-repeat='tag in Tags')
                                li
                                    label
                                        input(ng-model='newpost.tag',value='{{tag.name}}', type='checkbox', name='tag[]')
                                        span {{tag.name}}
                    button( ng-click='createPost(newpost)', class='btn btn-small btn-primary') Create Post

我不确定将我的视图绑定到模型有什么问题。标签被渲染并且复选框被创建,但是当我选中一个复选框时,所有这些复选框都会被检查。

1 个答案:

答案 0 :(得分:0)

input(ng-model='newpost.tag', ng-value-true='tag.name', ng-value-false='null' type='checkbox', name='tag[]')

Docs Input[checkbox]