Angular JS Magazine

vineri, 19 septembrie 2014

Explicitly Updating the Scope

Most of the time Angular JS will automatically update the scope for us. But, sometimes, you need to use Angular with other JavaScript libraries, and, in such cases, you need to know that this is possible via three methods listed in the below image (source of this image: Pro AngularJS, by Adam Freeman):

Now, based on this methods, you can see an example of putting Angular and jQuery together. Next tip uses a jQuery Spinner that can be:

- enabled/disabled from Angular
- queried for its value on mouse wheel and display that value via Angular

The code is:

<!DOCTYPE html>
<html ng-app="appModule">
<head lang="en">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../jquery/jquery-ui.css">
    <script src="../angular/angular.min.js"></script>
    <script src="../jquery/external/jquery/jquery.js"></script>
    <script src="..//jquery-mousewheel/jquery.mousewheel.js"></script>
    <script src="..//jquery/jquery-ui.js"></script>
        //jQuery code
        $(document).ready(function () {
            $(function () {
                var spinner = $("#spinner").spinner();
                $('#spinner').bind('mousewheel', function (e) {
                        $apply('handleSpinnerValue(' + $("#spinner").spinner("value") + ')');

        //Angular code
        angular.module("appModule", [])
                .controller("appCtrl", function ($scope) {
                    $scope.spinnerEnabled = true;

                    $scope.handleSpinnerValue = function (sv) {
                        $scope.spinnerValue = sv;

                    $scope.$watch('spinnerEnabled', function (spinnerEnabled) {

                        //with spinnerEnabled
                        if (spinnerEnabled) {
                        } else {
                        //without spinnerEnabled
                         if ($("#spinner").spinner("option", "disabled")) {
                         } else {
<body ng-controller="appCtrl">

<div id="spinnerDivId">
    <input type="checkbox" ng-model="spinnerEnabled"> Enable Spinner
        <label for="spinner">Select a value:</label>
        <input id="spinner" name="value">
        Spinner Value In Angular (changes only on mouse wheel): {{spinnerValue}}