I have an app with two routes/templates login and main. The login template's user input values are bound to two scope variables username
and isAdmin
. The scope variables are initialized with 'abc' and false, on app startup.
Problem ->
The controller function is always bound to the same initial values which are given on application startup. It does not reflect the scope variables that are being changed on login template
Used {{ }} on markup to see if the binding is happening correctly, the interpolated part actually reflects the value being changed.
Please help if doing it wrong.
app.controller('appController', function() {
$scope.username = "abc"
$scope.isAdmin = false;
this.radioChange = function() {
console.log($scope.isAdmin) // consoles initialized value always
}
this.textChanged = function() {
console.log($scope.username) // doesn't reflect changed value, shows "abc"
}
})
login Template:
<input type="radio" ng-model="isAdmin" ng-value="true" ng-
change="ctrl.radioChange()">
<input type="radio" ng-model="isAdmin" ng-value="false" ng-
change="ctrl.radioChange()">
<input type="text" ng-model="username" ng-change="ctrl.textChanged()">
{{isAdmin}} // view binded correctly to change
{{username}}
index.html
<body ng-controller="appController as ctrl">
<ui-view> </ui-view>
</body>
app.config
app.config(['$stateProvider', '$urlRouteProvider', function($stateProvider,
$urlRouterProvider) {
var login = { name: 'login', url: '/', controller='appController',
templateUrl: 'login.html'}
var main = { name: 'main', url: '/main', controller='appController',
templateUrl: 'main.html'}
$stateProvider.state(login);
$stateProvider.state(main);
$urlRouterProvider.otherwise('/');
}])
This seems to be happening because the login template code has a scope (parent) different from appcontroller
scope (child).
While child scope can read properties from parent, changes to these properties (primitive types specifically) create a new property on child scope.
Get rid of appController
from the body, instead use the controller association done through route (which you partially have):
var login = { name: 'login', url: '/', controller='appController as ctrl',
templateUrl: 'login.html'}
$stateProvider.state(login);
Also it would be better that you avoid scope if using a controller as approach, hence input becomes
<input type="text" ng-model="ctrl.username" ng-change="ctrl.textChanged()">
Finally this will help you understand issues with scope inheritance https://github.com/angular/angular.js/wiki/Understanding-Scopes