koushik R koushik R - 2 months ago 6
AngularJS Question

Dynamic property on JavaScript object getting null

I'm trying to set the dynamic property on a javascript object using the ng-model. But I'm unable to create it as I always get null for that property. I have different ways to copy the value from the variable self.username to self.params javascript object in the below code.

Please see this plnkr

index.html

<!DOCTYPE html>
<html ng-app="myApp">

<head>
<link rel="stylesheet" href="style.css">
<script src="//code.angularjs.org/1.2.26/angular.js"></script>
<script src="https://code.angularjs.org/1.2.26/angular-route.min.js">
</script>
<script src="app.js"></script>
<script src="routes.js"></script>
</head>

<body>
<a href="#/carriers">Carriers</a>

<div class="mainContainer" ng-view></div>
</body>

</html>


routes.js

myApp.config(function($routeProvider) {
$routeProvider
.when('/carriers', {
templateUrl: 'carriers.html',
controller: 'MainCtrl',
controllerAs: 'mainCtrl'
})
.otherwise({
redirectTo: '/'
});
});


Carriers.html

<input type="text" placeholder="username" ng-model="mainCtrl.username" />
<button ng-click="mainCtrl.login()">Login</button>


app.js

var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('MainCtrl', function() {
var self = this;
self.username = '';
self.login = login;
self.params = {
username: self.username //doesnt work
};
//self.params.username=angular.copy(self.username); //doesnt work
//self.params['username']=self.username; //doesnt work
function login() {
// alert(self.username);
console.dir(self.username); // works
console.dir(self.params); // username:'' getting empty string for username property
}
});

Answer

The value does not update because you created a new object and set the value of self.params.username to the value of self.params. self.params.username does not reference self.params it was just set from the value when the object was created.

If you want to bind self.params.username to the input then you can change your input model to:

<input type="text"  placeholder="username" ng-model="mainCtrl.params.username" />

Another alternative is to watch self.username and set the value of self.params.username to the new value using $watch

// watch mainCtrl.username for any changes
$scope.$watch('mainCtrl.username', function(newValue, oldValue) {

    // set self.params.username from the new value
    self.params.username = newValue;

});
Comments