Salih Mohamed Salih Mohamed - 25 days ago 16
Javascript Question

AngularJS input field value not showing when using ng-model

The input fields values not showing in the input fields. I used both ng-model & data-ng-model. Without using ng-model the values are displaying.

i.e 1:

<input type="text" value="{{accountDetailsBody.phoneNumber}}" data-ng-model="vm.user.phoneno" name="phoneno" id="phoneno" class="form-control">


i.e 2:

<input type="email" name="email" class="form-control" id="email" ng-model="vm.user.email" readonly ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/" placeholder="Email" ng-maxlength="30" required>


Controller

(function () {
'use strict';
angular
.module('app')
.controller('accountController', accountController);
accountController.$inject = ['ApiService', '$rootScope', 'UserService', '$scope', '$location'];
function accountController(ApiService, $rootScope, UserService, $scope, $location) {
$scope.accountDetailsBody = {};
var vm = this;
vm.userUpdate = userUpdate;

initController();
function initController() {
loadCurrentUser();
}

function userUpdate() {
console.log(vm.user);
}

function loadCurrentUser() {
$scope.data = {'email': $rootScope.globals.currentUser.username};
UserService.GetByUsername($scope.data).then(function (response) {
if (response.success) {
$scope.accountDetailsBody = response.user[0];
} else {
$location.path('/');
}
//vm.user = user;
});
}
}

})();

Answer

Don't need to set value here. you can bind value directly to input text box with ng-model

try with this

Controller

    (function () {
        'use strict';
        angular
                .module('app')
                .controller('accountController', accountController);
        accountController.$inject = ['ApiService', '$rootScope', 'UserService', '$scope', '$location'];
        function accountController(ApiService, $rootScope, UserService, $scope, $location) {

            var vm = this;
            vm.accountDetailsBody = {};
            vm.userUpdate = userUpdate;

            initController();
            function initController() {
                loadCurrentUser();
            }

            function userUpdate() {
                console.log(vm.user);
            }

function loadCurrentUser() {
            $scope.data = {'email': $rootScope.globals.currentUser.username};
            UserService.GetByUsername($scope.data).then(function (response) {
                if (response.success) {
                    vm.accountDetailsBody = response.user[0];
                } else {
                    $location.path('/');
                }
                //vm.user = user;
            });
        }
        }

    })();

HTML

<input type="text" ng-model="vm.accountDetailsBody.phoneNumber" name="phoneno" id="phoneno" class="form-control">
Comments