babyshark
babyshark

Reputation: 65

Angular JS: attribute not influenced by $scope...?

Angular newbie here. I have the following div:

<div id="mainfr" data-curpos="dy[ {{curPosObj.dy}} ]" ...>blah blah </div>

And in my controller I have:

var nxtest = angular.module('nxtest', []);
var appController = nxtest.controller('AppCtrl', ['$scope', function ($scope) {
    $scope.curPosObj = { dir: "down", dy:5 };
    $scope.clr = window.setTimeout(function(){ $scope.curPosObj.dy = 777;
window.clearTimeout($scope.clr); }, 5000); //see if the attr responds to a random change
}])

In firebug, inspecting the scope object shows that it is indeed modified. I want to understand why the bound attribute {{curPosObj.dy}} is not 'bound' and the view does not respond to the changing values? Thanks very much in advance.

Update: added link to plunker as suggested - the red text never changes: http://plnkr.co/edit/HJxEpgR8VepxuT47zJDJ?p=preview

Update 2: OK so there may be a separate issue here - the red text is in a pseudo element whose contrent attribute depends on the main divs attribute... and I'm not calling setAttribute anywhere... but regardless: in firebug, the 'data-curpos' attribute itself is NOT updating, never mind the pseudo elem that depends on it...

Upvotes: 0

Views: 40

Answers (1)

IUnknown
IUnknown

Reputation: 22448

That's because angular doesn't tracking scope changes out of the dygest cycle and window.setTimeout that case. You should use the $timeout service instead of window.setTimeout or put code which chenge scope into $scope.$apply call

angularjs API reference - $timeout service

angularjs API reference - scope guide

try this:

var nxtest = angular.module('nxtest', []);
var appController = nxtest.controller('AppCtrl', ['$scope', '$timeout',
  function($scope, $timeout) {
    $scope.curPosObj = {
      dir: "down",
      dy: 5
    };
    $scope.clrPromise  = $timeout(function() {
      $scope.curPosObj.dy = 777;
    }, 5000); //see if the attr responds to a random change

} ])

Upvotes: 1

Related Questions