Thursday, January 28, 2016

Angular: assign asyncronous value to scope

A simple example on how to assign an asyncronous value to a scope property (var2) and comparing it to a common value assignment.

<div ng-app="AppName" ng-controller="OneController">
Scope with initial value: {{var1}}<br>
Scope with new value: {{var2()}}
</div>

<script src="http://code.angularjs.org/1.2.14/angular.min.js"></script>
<script>
angular.module('AppName', []);

angular.module('AppName').controller('OneController', ['$scope', '$interval', function($scope, $interval) {
    var asyncvar = 'old value';
    $interval(function() { asyncvar = 'new value'; }, 1000 , 1);
    $scope.var1 = asyncvar;
    $scope.var2 = function() { return asyncvar; } //assign asyncronous value to scope
}]);
</script>

No comments:

Post a Comment