当控制器中的范围值发生更改时,AngularJS ng-model不会更新

时间:2016-04-08 12:54:25

标签: javascript angularjs

在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不会更新。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

尝试对span:AngularJS - ng-model fails on <span>

使用ng-bind
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>

或仅<span class="md-headline">{{user.displayName}}</span>

答案 1 :(得分:0)

您可以使用

<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"