You can use $rootScope
instead $scope
but your variable will be "global" and all controllers (if you have more then one) will see it.
But advantage of angular will be lost a bit. Because all models (a.e ng-model
) will be created under specific $scope
but not $rootScope
For each controller define private $scope
.
so if you use two controllers in both you can define the variable name:
$scope.data = "AAA";
and in other controller:
$scope.data = "BBB";
they are different because refer to different instances (aka controllers)
about your problem:
you created this lines:
First Name: <input type="text" ng-model="fname" required>
Last Name: <input type="text" ng-model="lname" required>
under controller myCtrl1
. therefore it will not update your $rootScope
but $scope
that refers to myCtrl1
.
I think you can use ng-change
to notify $rootScope
about change.
add to HTML:
First Name: <input type="text" ng-model="fname" ng-change ="onfnameChange(fname)" required>
Last Name: <input type="text" ng-model="lname" ng-change ="onlnameChange(lname)" required>
to controller:
...
$scope.onfnameChange = function(val){
$rootScope.fname = val;
};
$scope.onlnameChange = function(val){
$rootScope.lname = val;
};
...
see Fiddle