How to change AngularJS data outside the scope

Posted on February 18, 2016 by Suresh Kamrushi in Javascript

Today I learn how to update scope data outside of controller or app. Angular have $scope.$apply() method which will explicitly update your binded data.
Sharing sample code how I did that:

 <div ng-app="mySampleApp" ng-controller="sampleCtrl">
<input type="button" value="Change to 'test data'" ng-model="data" onclick="change()">

Angular JS code

var app = angular.module('mySampleApp', []);
app.controller('sampleCtrl', function($scope, $http) {
  $scope.mydata = "Dummy Text";

function change() {
   //if you have single controller in your page than you can do like this
    var appElement = document.querySelector('[ng-app=mySampleApp]');
   // you have multiple controller inside single app than you can do like this:
    //var appElement = document.querySelector('[ng-controller=sampleCtrl]');
    var $scope = angular.element(appElement).scope();
    $scope.$apply(function() {
        $scope.mydata = 'test data';

Sample Fiddle
A good article about $apply.