在角度中传递隐藏值

时间:2015-11-02 19:52:45

标签: angularjs hidden-field ng-init angularjs-ng-value

查看:

  <ul ng-repeat="x in posts.post">
      {{x.name}}  {{x._id}} {{x.post}} {{x.user_id}} 
      <br>
      <ul ng-repeat="y in x.comment">
        {{y.comment}}
      </ul>
      <input type="text" style="display: none;" ng-model='new_comment.userId' value={{users2.id}} name="userId"  >
      <input type="text" style="display: none;" ng-model='new_comment.name' value={{users2.name}} name="userName"   >
      <textarea ng-model='new_comment.comment' name="comment" rows="4" cols="50">
      </textarea> 
      <br>
      <input type="submit" value="Post Comment!" ng-click="addComment(x._id, new_comment)">
  </ul>

控制器:

UserFactory.getUser(function (data) {
    $scope.users2 = data;
});

工厂:

factory.getUser = function(callback) {
    $http.get("/user").success(function(output) {
        users2 = output;
        callback(users2);
    });
};

我试图将控制器/工厂中的users2.id和users2.name的隐藏值传递给表单。我尝试了ng-init,ng-value以及输入类型=&#34;隐藏&#34;但是没有效果。

所以这就是我为实现目标所做的工作

查看:

  <form>

  <textarea ng-model='new_comment.comment' name="comment" rows="4" cols="50">
  </textarea> 

  <br>
  <input type="submit" value="Post Comment!" ng-click="addComment(x._id, new_comment, users2.name, users2._id)">
  </form>

控制器:

$scope.addComment = function(id, comment, userName, userId) {

var commentValue = comment.comment;

var newComment = {comment: commentValue, name: userName, userId: userId};

postFactory.addComment(id, newComment, function () {

    postFactory.getComment(function (data) {
        $scope.comments = data;
    });

    $scope.new_comment = {};
});
};

3 个答案:

答案 0 :(得分:1)

试试这个

  <input type="hidden" ng-model='new_comment.userId' value="{{users2.id}}" name="userId"  >

当你在改变事物时

UserFactory.getUser
.then(function (data) {
    $scope.users2 = data;
});

factory.getUser = function() {
    return $http.get("/user");
};

$ http返回一个承诺

答案 1 :(得分:1)

双向绑定不适用于hidden元素,因此我使用ng-value设置type="hidden"元素的值

<input type="hidden" ng-value='new_comment.userId' name="userId"/>
<input type="hidden" ng-value='new_comment.name' name="userName"/>

答案 2 :(得分:0)

做这样的事情,回报承诺。

factory.getUser = function(callback) {
    return $http.get("/user")
};

控制器:

UserFactory.getUser().success(function(output) {
    $scope.users2 = output.data;
});