2015-09-16 114 views
0

我使用alanning模板設置複選框:角色檢查角色:流星:設置幫手

helper.js

Template.user.helpers({ 
    var loggedInUser = Meteor.user() 
    var admin = (Roles.userIsInRole(loggedInUser, ['admin'])) ? true : false, 
     editor = (Roles.userIsInRole(loggedInUser, ['admin'])) ? true : false; 
    var roles = { admin: admin, editor: editor }; 
    return roles; 
}); 

模板

<template name="user"> 
    <form> 
     <input type="checkbox" name="admin"> Admin 
     <input type="checkbox" name="editor"> Admin 
    </form> 
</template> 

如何如果管理員或編輯者是真的,我會設置複選框來檢查嗎? 還是有更好的方法來設置複選框選中?

+0

首先,你應該再次檢查助手是如何製造 – Sindis

回答

2

一般情況下,你要初始化你的模板的狀態在其onRendered回調是這樣的:

Template.user.onRendered(function() { 
    var userId = Meteor.userId(); 
    $('input[name=admin]').prop('checked', Roles.userIsInRole(userId, ['admin'])); 
    $('input[name=editor]').prop('checked', Roles.userIsInRole(userId, ['editor'])); 
}); 

注意,根據docsuserIsInRole有一個id(不是對象)。

如果你有多個角色來檢查,你可以在它們之間迭代,像這樣:

Template.user.onRendered(function() { 
    var userId = Meteor.userId(); 
    var roles = ['admin', 'editor']; 
    _.each(roles, function(role) { 
    $("input[name=" + role + "]").prop('checked', Roles.userIsInRole(userId, [role])); 
    }); 
}); 
+0

我會用一個字段列表,並遍歷這個。那我就不需要這個數組了 – user3142695

0

您可以相應地設置他們在頁面加載到這樣的用戶角色:

Template.users.rendered = function() { 
    var self = this; 
    var loggedInUser = Meteor.userId(); 
    var admin = (Roles.userIsInRole(loggedInUser, ['admin'])), 
     editor = (Roles.userIsInRole(loggedInUser, ['editor'])); 
    //set the checkboxes correct values 
    $(self.find("#admin")).prop('checked', admin); 
    $(self.find("#editor")).prop('checked', editor); 
}; 

如果你需要被動地設置您的複選框的狀態,這裏是你如何進行:

HTML

<template name="user"> 
    <form> 
     <input type="checkbox" name="admin" {{getValueForChecked "admin"}}> Admin 
     <input type="checkbox" name="editor" {{getValueForChecked "editor"}}> Editor 
    </form> 
</template> 

JAVASCRIPT

Template.user.helpers({ 
    "getValueForChecked": function(value){ 
    var loggedInUser = Meteor.userId(); 
    var credentials= (Roles.userIsInRole(loggedInUser, [value])); 
    return credentials? "checked" : "" 
    } , 
    //or alternatively you can use one helper per field 
    "isAdmin": function(){ 
    var loggedInUser = Meteor.userId(); 
    var admin = (Roles.userIsInRole(loggedInUser, ['admin'])); 
    return admin ? "checked" : "" 
    }, 
    "isEditor": function(){ 
    var loggedInUser = Meteor.userId(); 
    var editor = (Roles.userIsInRole(loggedInUser, ['editor'])); 
    return editor? "checked" : "" 
    } 
});