0

My problem: I can modify my model fine, and the changes are reflected in my view, as long as my view is hidden. As soon as my view is un-hidden, changes made to scope.food.foo from timeouts, event handlers, etc. no longer apply. This is all within a directive.

Fiddley: http://jsfiddle.net/9T9qE/1/

I am using an object as my model (instead of using the scope as my model, which causes problems with inheritance) That is, I'm using scope.food.foo instead of simply scope.foodFoo

html:

<div ng-app="myApp">
    <my-directive></my-directive>
</div>

js:

myApp = angular.module("myApp", []);

myApp.directive("myDirective", function() {
    var d = {};
    d.restrict = "E";
    d.template = '<div ng-show="food.show">hi, I like <input type="text" ng-model="food.foo">   and, in case you forgot, that\'s {{food.foo}}</div><button ng-click="food.show = true">show me</button>';
    d.link = function(scope, element, attrs) {
        scope.food = {};
        scope.food.foo = "pie";
        scope.food.show = false;
        setTimeout(function() {
            alert("timeout: setting scope.food.foo = 'cake'");
            scope.food.foo = "cake";
        }, 6000);
    };
    return d;
});
Ryan S
  • 195
  • 2
  • 11

1 Answers1

1

How can I tell AngularJS to "refresh"

looks like the answer is scope.$appy() - that worked for me. http://jsfiddle.net/XR9s2/1

    setTimeout(function() {
        alert("timeout: setting food.foo = 'cake'");
        scope.$apply(function() { food.foo = "cake"; });
    }, 6000);

This article, referenced from the above question, helped me too: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

Edit: from that article:

Sometimes I see examples where data is updated, and then $scope.$apply() is called with no arguments. This achieves the desired result, but misses some opportunities.

If your code isn’t wrapped in a function passed to $apply, and it throws an error, that error is thrown outside of AngularJS, which means any error handling being used in your application is going to miss it. $apply not only runs your code, but it runs it in a try/catch so your error is always caught, and the $digest call is in a finally clause, meaning it will run regardless of an error being thrown. That’s pretty nice.

I changed my code above to reflect that: instead of changing the value, then using scope.$apply(), I did scope.$apply(function() { /* change value */ });

Community
  • 1
  • 1
Ryan S
  • 195
  • 2
  • 11