Angular JS – ngChange and access to $scope from outside

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Angular JS</title>
</head>
<body data-ng-app="myApp">
    <div id="angular-view" data-ng-controller="myController">
        <select ng-model="selectValue" ng-change="selectChanged()">
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
        </select>
        <p>{{ selectRelatedValue() }}</p>
    </div>
 
    <!--External button-->
    <button id="btn-change-sel-value">Change Select Value</button>
 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
 
    <script>
        angular.module("myApp", ["myApp.controllers"]);
 
        angular.module("myApp.controllers", []).controller("myController", function ($scope) {
            $scope.selectValue = 1;
            $scope.selectRelatedValue = function () {
                return "Select Related Value " + $scope.selectValue;
            };
 
            //Trigger changes on the selected option
            $scope.selectChanged = function () {
                alert("Selected value = " + $scope.selectValue);
            };
            $scope.changeSelectValue = function (value) {
                $scope.selectValue = value;
 
                //I'm updating the selected value by code,
                //so I have to manually call the event (as
                //for a normal JS event)
                $scope.selectChanged();
            };
        });
 
        //External button management
        $("#btn-change-sel-value").bind("click", function () {
 
            //To update the scope from outside
            //I have to use the $apply method
            var scope = $("#angular-view").scope();
            scope.$apply(function () {
                scope.changeSelectValue(2);
            });
        });
    </script>
</body>
</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s