How can I avoid $ scope. $ apply () in callback
Below code works fine. I'm just trying to figure out if there is a better way to write it so that I can avoid it $scope.$apply()
in my controller.
When the user clicks the button "Sign Up"
, the call goes to the controller and then to the service along with the callback method. In the service, I call Parse Cloud Code to create a user and call a Callback after receiving a response.
The problem is that I have to call $scope.$apply()
in the callback method to apply the changes to the vm.m.resp
range bound property .
Is it possible to run the entire registration process as a single transaction and avoid the callback?
OR
Is there a way to avoid the call $scope.$apply()
?
This is how my user interface looks like:
<ion-view title="Sign Up">
<ion-content class="has-header">
<div class="list">
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text" ng-model="vm.m.username">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" ng-model="vm.m.password">
</label>
<label class="item">
<button class="button button-block button-positive" ng-click="vm.doSignUp()">Sign Up</button>
</label>
</div>
<div class="list">
<div class="bar bar-header bar-positive">
<span ng-bind="vm.m.resp"></span>
</div>
</div>
</ion-content>
</ion-view>
This is what my controller looks like:
(function () {
'use strict';
angular.module('app').controller('UserAdminCtrl', ['$stateParams', '$scope', 'userAdminApi', UserAdminCtrl]);
function UserAdminCtrl($stateParams, $scope, userAdminApi) {
var vm = this;
vm.m = {};
vm.m.username = '';
vm.m.password = '';
vm.m.resp = '';
function doSignUp() {
userAdminApi.doSignup(vm.m, doSignUpCallback);
vm.m.resp = 'Signing up. Please wait...';
}
function doSignUpCallback(resp) {
vm.m.resp = resp;
$scope.$apply()
}
vm.doSignUp = doSignUp;
vm.doSignUpCallback = doSignUpCallback;
};
})();
This is what my service looks like:
(function () {
'use strict';
angular.module('app').factory('userAdminApi', [userAdminApi]);
function userAdminApi() {
function doSignup(m,cb) {
Parse.Cloud.run('createUser', {m}, {
success: function (result) {
cb(result);
},
error: function (error) {
cb(error.message);
}
});
}
return {
doSignup: doSignup
};
};
})();
source to share
You can use a promise to return to the digest loop:
(function () {
'use strict';
angular.module('app').factory('userAdminApi', ['$q', userAdminApi]);
function userAdminApi($q) {
function doSignup(m) {
var deferred = $q.defer();
Parse.Cloud.run('createUser', {m}, {
success: function (result) {
deferred.resolve(result);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise;
}
return {
doSignup: doSignup
};
};
})();
This will give you a nice and clean callback.
source to share