javascript - un-hiding a data-bound thing ( ng-model or {{food.foo}} ) breaks the binding -


my problem: can modify model fine, , changes reflected in view, as long as view hidden. view un-hidden, changes made scope.food.foo timeouts, event handlers, etc. no longer apply. within directive.

fiddley: http://jsfiddle.net/9t9qe/1/

i am using object model (instead of using scope model, causes problems inheritance) is, i'm using scope.food.foo instead of 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, <input type="text" ng-model="food.foo">   and, in case 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; }); 

how can tell angularjs "refresh"

looks answer scope.$appy() - worked me. http://jsfiddle.net/xr9s2/1

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

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

edit: article:

sometimes see examples data updated, , $scope.$apply() called no arguments. achieves desired result, misses opportunities.

if code isn’t wrapped in function passed $apply, , throws error, error thrown outside of angularjs, means error handling being used in application going miss it. $apply not runs code, runs in try/catch error caught, , $digest call in clause, meaning run regardless of error being thrown. that’s pretty nice.

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


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -