rpacker
rpacker

Reputation: 3

Why is the AngularJS binding not working even though the $scope property is getting updated?

I am new to AngularJS and am struggling to get the binding down. In the simple example below, I'm trying to update the UI to show the value of the jquery slider (I understand there is a pure Angular way to solve this, but this is just my reduction test case, and it would still be very helpful for me to understand why changing $scope.slider_value does not update the view). What am I missing?

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/flick/jquery-ui.css" />        
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
        <script type="text/javascript">

            var testApp = angular.module('testApp', []);
            testApp.controller('testCtrl', function($scope) {
                $('#slider').slider({
                    max: 1000,
                    slide: function( event, ui ) {
                        $scope.slider_value = ui.value;
                    }
                });
                $scope.slider_value = 0;
            });

        </script>
        <style>
            #slider { margin: 20px; }
            #to_update { margin: 10px; font-family: Arial; }
        </style>
    </head>
    <body ng-app="testApp">
        <div ng-controller="testCtrl">
            <div id="slider"></div>
            <div id="to_update">slider value: {{ slider_value }}</div>
        </div>
    </body>
</html>

Upvotes: 0

Views: 473

Answers (1)

NG.
NG.

Reputation: 22904

You are updating the scope via an event angular does not know about. In this case, you need to wrap the updates in a $apply.

Try this:

slide: function( event, ui ) {
    $scope.$apply(function() {
        $scope.slider_value = ui.value;
    });
}

Check out the documentation on scope.$apply

Upvotes: 1

Related Questions