dssnh86244 2018-12-21 02:44 采纳率: 100%
浏览 254

AngularJS ng-model无法从输入字段获取数据

I encounter a problem about AngularJS I can't get the data from the input field.

This is my HTML input field:

<input ng-model="dnameform" ng-init="dnameform=user.user_displayname" type="text">

And this is how I retrieve data on JavaScript:

$scope.dnameform
  • 写回答

2条回答 默认 最新

  • dongliuliu0385 2018-12-21 04:29
    关注

    In this ng-init would result into inappropriate behavior, if user object is loaded from API service call, the ng-init directive fires before than that. So dnameform value will be always undefined.

    Rather I believe you should directly use user.user_displayname as in ng-model no need of creating new ng-model variable.

    <input ng-model="user.user_displayname" type="text">
    

    And wherever you need a value, you can directly use $scope.user.user_displayname


    OR

    You can do assignment of dnameform variable from controller, when user API service call finishes off. Then you're free to use dnameform as in ng-model on input field without ng-init.

    apiService.getUser().then(function(res){
       $scope.user = res.data
       $scope.dnameform = user.user_displayname;
    }) 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条