简体   繁体   中英

Angular.js deep watch Coffeescript class instance

I have a CoffeeScript class like this:

class Foo
    constructor: (@bar) ->
        setTimeout () =>
            @bar = "changed!"
        , 5000)

And a list like this in my controller:

$scope.list = [new Foo("1"), new Foo("2")]

I have HTML like this:

<ul>
    <li ng-repeat="baz in list">
        {{baz.bar}}
    </li>
</ul>

After 5 seconds, the values of the items in $scope.list change, but this is not reflected in the HTML.

Things are partially connected properly because if I add this code, everything works fine (albeit on a slight delay). The HTML is redrawn and updated properly.

setInterval () ->
    $scope.$apply () ->
        $scope.crashes = $scope.crashes
, 5000)    

Is there any way to make sure the HTML updates when the properties on CoffeeScript class changes?

Did you try:

$scope.$watch('crashes', function (newVal) {
  $scope.crashes = newVal
}, true);

Setting the last param of $watch to true makes it a deep watch.

Don't use setTimeout since angularJS won't track changes and you will need to call $scope.$apply as you did. Use $timeout .

Edit: You can improve the custom timeout solution you posted by using $timeout and delete both the setInterval and the apply.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM