Angularjs中的动态ng-init设置值

时间:2016-03-17 08:03:47

标签: javascript angularjs ng-init

我想在页面加载时启动ng-init。我有task.id获取Restangular,我的html是:

<textarea rows="5" ng-model="comment.comment_text"></textarea>{{task.id}}
<input type="hidden" ng-model="comment.task_id" ng-init="comment.task_id = $scope.task.id">   
<button type="submit" class="btn btn-success" ng-click="create(comment)">Send</button>

和角度控制器:

$scope.create = function(comment) {
     console.log(comment);
};

单击按钮在控制台中显示结果时:

{comment_text: "test", task_id: undefined }

但我想这样表现出来:

{comment_text: "test" ,task_id:53}

2 个答案:

答案 0 :(得分:1)

尝试:

ng-init="comment.task_id = task.id"

或者您可以从控制器

进行设置
$scope.comment.task_id  =$scope.task.id

或输入值

<input type="hidden" ng-model="comment.task_id" value="{{task.id}}" />  

答案 1 :(得分:0)

尝试

<textarea rows="5" ng-model="comment.comment_text"></textarea>{{task.id}}
<input type="hidden" ng-model="comment.task_id" ng-init="comment.task_id = task.id">   
<button type="submit" class="btn btn-success" ng-click="create(comment)">Send</button>