如何使用javascript访问sails.js模型中的属性?

时间:2016-05-11 09:03:40

标签: javascript node.js model sails.js

我想在编辑视图中访问某些属性来更改某些值。

我尝试使用类似<%=course.scoreAlgo=>的内容进行访问,但这不起作用。

我似乎无法访问script标记内的模型中的任何属性。任何和所有帮助我如何访问这一点非常感谢!

课程模型:

module.exports = {

  attributes: {
    code:{
      type: "string"
    },

    name:{
      type: "string"
    },

    recitations:{
      type: 'array',
      defaultsTo: 0
    },

    finishedAssignments:{
      type: "array"
    },

    recitationScore:{
      type: 'integer',
      defaultsTo: 0
    },

    recitationGroup:{
      type: "string",
      defaultsTo: "none"
    },

    shown:{
      type: "string",
      defaultsTo: "no"
    },

    scoreAlgo:{
      type:"array"
    },

    takes:{
      model: 'student'
    }
  }
};

这就是我正在尝试制作的代码:

<form action="/course/update/<%= course.id %>" method="POST">
  <h2>Edit course</h2>
  <input value="<%= course.code%>" type="text" name="code"><br/>
  <input value="<%= course.name%>" type="text" name="name"><br/>
  <input value="<%= course.shown %>" type="text" name="shown"><br/>
  <input value="<%= course.recitationScore%>" type="text" name="recitationScore"><br/>
  <p>Score algo, specify by saying how many have to be completed for each "subgroup".
    If two from a, two from b and one from c means full score, put "2,2,1"</p>
  <input value="<%=course.scoreAlgo%>" type="text" name="scoreAlgo">
  <input type="button" value="Calculate recitationScore" onclick="calcScore()">
  <script>
    function calcScore(){
      var stringArray = course.finishedAssignments;
      var scoreAlgo = course.scoreAlgo;
      for(var i=0; i < stringArray.length; i++){
        var str = stringArray[i];
        var sStr = str.split(",");
        for(var j=0; j < sStr.length; j++){
          var count = scoreAlgo[i]
          var s = sStr[i];
          var sS = s.split((i+1).toString);
          if(sS.length >= count){
            var score = sS.length*33;
            course.recitationScore = course.recitationScore + score;
            console.log(score);
          }
        }
      }
    }
  </script>
  <input type="submit" value="Edit course"/>
</form>

1 个答案:

答案 0 :(得分:0)

您传递给.ejs并希望显示的所有值,即使在<%= %>

中也需要用<%- %><script></script>打包
function calcScore(){
  var stringArray = <%= course.finishedAssignments %>;
  var scoreAlgo = <%= course.scoreAlgo %>;
  for(var i=0; i < stringArray.length; i++){
    var str = stringArray[i];
    var sStr = str.split(",");
    for(var j=0; j < sStr.length; j++){
      var count = scoreAlgo[i]
      var s = sStr[i];
      var sS = s.split((i+1).toString);
      if(sS.length >= count){
        var score = sS.length*33;
       //course.recitationScore = course.recitationScore + score; <!- not sure what should it do
        console.log(score);
      }
    }
  }
}