Reputation: 565
I have this...
<script> var num = 22;</script>
Then inside of the controller block...
<span>{{somenumber}}</span>
In the controller...
$scope.somenumber = num;
This all works as expected.
How would I go about having it all update if the value of the num variable changes? So, I'd have some code (from socket.io or AJAX) change num to 65. Right now, it still says 22.
Upvotes: 0
Views: 86
Reputation: 5753
I'd take a look at this
num
is a primitive type (Number). So When you're assigning it to the $scope
you're copying it. What you need to do is reference it instead. I'd fix it the following way.
<script>var value = {num: 22} </script>
$scope.value = value;
<span> {{value.num}} </span>
If your ajax call is not through $http
.(outside angular - wherever you set value.num
) you'll need to invoke a digest cycle. The easiest way to do that is in an angular service like $timeout
.
Think of the scope as
$scope
HAS model instead of$scope
AS model
Upvotes: 3
Reputation: 4887
You could use $watch
followed by $apply
:
Controller
$scope.somenumber = num;
$scope.$watch(function() {
return num;
}, function(newValue, oldValue) {
$scope.somenumber = newValue;
});
// fake external change to the 'num' variable
setTimeout(function() {
num = 33;
$scope.$apply();
}, 3000);
Here's a working example: http://plnkr.co/edit/rL20lyI1SgS6keFbckJp?p=preview
If your external change is happening outside the scope of a single controller, I would use $rootScope
inside a run
callback:
angular.module('exampleApp', []).run(function($rootScope) {
// same as above, just with $rootScope
});
Upvotes: 0