如何使用angularjs Checkbox绑定Mongoose模型

时间:2016-04-19 00:00:15

标签: angularjs mongodb mongoose meanjs

我正在尝试修改meanjs提供的示例应用程序 示例应用程序具有angularsjs视图,如下所示

  <input class="form-control" type="text" name="roles" 
  ng-model="vm.user.roles" id="roles" ng-list required />

更新角色的猫鼬模型部分如下。

/**
 * Module dependencies
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema,
  crypto = require('crypto'),
  validator = require('validator'),
  generatePassword = require('generate-password'),
  owasp = require('owasp-password-strength-test'),
  path = require('path'),
  logger = require(path.resolve('./config/lib/logger'));
/**
 * A Validation function for local strategy properties
 */
var validateLocalStrategyProperty = function (property) {
  return ((this.provider !== 'local' && !this.updated) || property.length);
};

/**
 * A Validation function for local strategy email
 */
var validateLocalStrategyEmail = function (email) {
  return ((this.provider !== 'local' && !this.updated) || validator.isEmail(email, { require_tld: false }));
};

var validateRoles = function (roles) {
  console.log("validate");
  return true;
};
/**
 * User Schema
 */
var UserSchema = new Schema({
  firstName: {
    type: String,
    trim: true,
    default: '',
    validate: [validateLocalStrategyProperty, 'Please fill in your first name']
  },
  lastName: {
    type: String,
    trim: true,
    default: '',
    validate: [validateLocalStrategyProperty, 'Please fill in your last name']
  },
  displayName: {
    type: String,
    trim: true
  },
  email: {
    type: String,
    unique: true,
    lowercase: true,
    trim: true,
    default: '',
    validate: [validateLocalStrategyEmail, 'Please fill a valid email address']
  },
  username: {
    type: String,
    unique: 'Username already exists',
    required: 'Please fill in a username',
    lowercase: true,
    trim: true
  },
  password: {
    type: String,
    default: ''
  },
  salt: {
    type: String
  },
  profileImageURL: {
    type: String,
    default: 'modules/users/client/img/profile/default.png'
  },
  provider: {
    type: String,
    required: 'Provider is required'
  },
  providerData: {},
  additionalProvidersData: {},
  roles: {
    type: [{
      type: String,
      enum: ['USR', 'ADM', 'SAD']
    }],
    default: ['USR'],
    required: 'Please provide at least one role',
    validate: [validateRoles, 'Please provide at least one role']
  },
  updated: {
    type: Date
  },
  created: {
    type: Date,
    default: Date.now
  },
  /* For reset password */
  resetPasswordToken: {
    type: String
  },
  resetPasswordExpires: {
    type: Date
  }
});

现在我正在尝试将上面的文本输入转换为复选框。我修改过的视图如下

  <label ng-repeat="rolename in vm.rolesnames">
  <input type="checkbox" text={{rolename}} 
  ng- checked="vm.chooserole(rolename)" ng-model="vm.user.roles">
  {{rolename}}
  </label>

我的Angularjs控制器更新角色如下

vm.rolesnames = ['USR', 'ADM', 'SAD']; //dummy for view
vm.userused = new Set(user.roles);// this is from model

function chooserole(rolename) {
  console.log("chooserole");
  if (rolename === 'USR') {
    return vm.userused.has('USR');
  } else if (rolename === 'ADM') {
    return vm.userused.has('ADM');
  } else if (rolename === 'SAD') {
    return vm.userused.has('SAD');
  }
  return false;
}

每当加载页面时,都会正确分配用户的角色,但每当我单击复选框时,所有三个复选框都会被选中。 如何将复选框绑定到枚举并将其发送到模型?

1 个答案:

答案 0 :(得分:0)

你的模特是什么样的?我建议使用ui-select https://github.com/angular-ui/ui-select而不是多个复选框,因为它更干净的UX和更少的控制器代码来维护。然后,您可以创建角色的枚举,并且可以对其进行管理,并且您的所有代码将继续使用该枚举角色。更容易管理。

angular.module('globals', [])
  .constant('Roles', ['USR', 'ADM', 'SAD']);

以下是我在用户模型中的属性:

  roles: {
    type: Array,
    default: ['USR']
  }

在我的控制器范围内,角色OR使用依赖注入来加载全局枚举/角色,如上所述:

$scope.rolesNames = ['USR', 'ADM', 'SAD];

对于前端/角度我使用UI选择

  {{user}}
  <br/>  
           <ui-select multiple ng-model="user.roles" theme="select2" ng-disabled="disabled" style="width: 300px;">
            <ui-select-match placeholder="Select roles...">{{ $item }}</ui-select-match>
            <ui-select-choices repeat="role in rolesNames">
              {{ role }}
            </ui-select-choices>
          </ui-select>