【问题标题】:AngularJS ng-model doesn't update when scope value changed in controller当控制器中的范围值更改时,AngularJS ng-model 不会更新
【发布时间】:2016-04-08 12:54:24
【问题描述】:

在 html 中:

<md-card-title-text ng-controller="ProfileCtrl">
  <span ng-model="user.displayName" class="md-headline">userName</span>
  <span ng-model="user.email" class="md-subhead">user@abc.com</span>
</md-card-title-text> 

在 angularjs 代码中:

angular.module('authApp')
  .controller('ProfileCtrl', function($scope) {
    $scope.user = {};
    $scope.user.displayName = localStorage.username;
    $scope.user.email = localStorage.email;
    console.log($scope.user.displayName)
  }); 

问题是 ng-model 在控制器中更改范围值时不会更新。我该如何解决这个问题?

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

尝试使用 ng-bind 作为 span:AngularJS - ng-model fails on <span>

angular.module('authApp')
    .controller('ProfileCtrl', function ($scope) {
        $scope.user = {displayName : 'userName', email: 'user@abc.com'};
        $scope.user.displayName = localStorage.username;
        $scope.user.email = localStorage.email;
        console.log($scope.user.displayName)
});

HTML:

<md-card-title-text ng-controller="ProfileCtrl">
     <span ng-bind="user.displayName" class="md-headline"></span>
     <span ng-bind="user.email" class="md-subhead"></span>
</md-card-title-text>

或者只是&lt;span class="md-headline"&gt;{{user.displayName}}&lt;/span&gt;

【讨论】:

    【解决方案2】:

    你可以使用

    <md-card-title-text ng-controller="ProfileCtrl">
       <span class="md-headline">{{user.displayName}}</span>
       <span class="md-subhead">{{user.email}}</span>
    </md-card-title-text>
    

    ng-bind-html="user.email"
    

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      相关资源
      最近更新 更多