0

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.

2 Answers 2

3

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

$scopeHAS model instead of $scopeAS model

Sign up to request clarification or add additional context in comments.

Comments

0

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.