【问题标题】:Passing hidden value in angular以角度传递隐藏值
【发布时间】:2016-02-02 19:31:59
【问题描述】:

查看:

  <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 以及 input type="hidden",但都没有。

所以这就是我为使其正常工作所做的工作

查看:

  <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 = {};
});
};

【问题讨论】:

  • $scope.users2 目前正在工作。当我在控制器中显示 console.log(data) 时。问题是在表单中提供数据并将其传递回控制器。

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


【解决方案1】:

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

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

控制器:

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

【讨论】:

    【解决方案2】:

    试试这个

      <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 返回一个承诺

    【讨论】:

      【解决方案3】:

      双向绑定不适用于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"/>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-13
        • 2021-05-08
        • 2019-08-17
        • 1970-01-01
        • 1970-01-01
        • 2016-07-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多