Within my angular application, I have a $scope
variable labeled as user
which contains a name
property.
Whenever I click on a link to set this user variable to "test":
<a href="#" ng-click="setUser()">Set User</a>
Using the following function:
$scope.user = {
name: 'blank'
}
$scope.setUser = function(name) {
$scope.user.name = name
}
This method works smoothly. However, when I attempt to set this variable within a promise.then()
block, it seems like the variable is updated correctly behind the scenes but Angular fails to reflect these changes in the view until another action is triggered on the $scope.user
.
<a href="#" ng-click="startLogin()">Set User</a>
The new approach involves calling a different function, startLogin()
:
$scope.user = {
name: 'blank';
};
$scope.setUser = function(name) {
$scope.user.name = name;
};
$scope.startLogin = function() {
var promise = Kinvey.ping();
promise.then(function(response) {
console.log('success');
$scope.setUser('test');
});
};
Even after implementing this revised process, the {{user.name}}
field remains as "blank" in the view.
I conducted some tests including:
- Ensuring that the
$scope
object is accessible and functional within the function by logging it to the console. - Confirming that logging
$scope.user
displays the updated value, indicating that the variable has indeed changed. - Interestingly, the view only updates upon clicking for a second time.
- Although applying
$scope.$apply()
resolves the issue temporarily, it doesn't seem like the most appropriate solution.
* The framework being utilized here is based on Kinvey, utilizing syntax similar to or identical with CommonJS's promise.then()