My Angular application features two routes that share the same controller and partials. Despite the shared code, the controller and partials behave slightly differently depending on the route being used. Here are the routes:
$routeProvider.when('/join', {templateUrl: '/partials/global-shared/join.html', controller: HouseJoinController});
$routeProvider.when('/join/:code', {templateUrl: '/partials/global-shared/join.html', controller: HouseJoinController});
Within the controller, I am checking if a code is provided, making an API call, and updating a model based on the API response:
if ($routeParams.code) {
API.post('signUp', 'invitedClient', 'getTenantDetails', {code: $routeParams.code}, function(result) {
$scope.firstName = result.client.firstName;
});
}
Additionally, the partial contains an input element that is linked to $scope.firstName
through ng-model
:
<input type="text" name="firstName" ng-model="firstName" ng-pattern="/^[a-zA-Z-']+[ ]?[a-zA-Z-']+$/" required>
Upon loading the page with a supplied code, I can see the API call and its results in Chrome's developer tools. I have also confirmed that $scope.firstName
is updated with the API result by utilizing console.log()
.
Despite this, the input element does not reflect the updated model. Strangely, if I include {{ firstName }}
just before the input element, the correct firstName
model is displayed.
After trying to use $scope.$apply()
within the API callback function as shown below:
if ($routeParams.code) {
API.post('signUp', 'invitedClient', 'getTenantDetails', {code: $routeParams.code}, function(result) {
$scope.$apply(function() {
$scope.firstName = result.client.firstName;
});
});
}
Angular throws an error stating: Error: [$rootScope:inprog]
.