Stack Overflow 17159652

by Gabriel Z

HTML

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
    <h1>Non Angular world</h1>
    <button id="change-dir1">Change attr1 on dir1 with jquery</button>
</div>

<div ng-app="myApp">
    <div ng-controller="MainCtrl">
      <h1>Angular world</h1>
      <dir1 id="d1" attr1="100"></dir1>
    </div>
</div>

JavaScript

var app = angular.module('myApp',[]);
app.controller('MainCtrl', function($scope) {

});
app.directive('dir1', function(){
  return {
    restrict: 'E',
    template : '<span style="padding:8px; border: 1px solid grey">dir1 attr = {{message}}<button ng-click="check()">check manually</button></span>',
    link : function(scope, el, attrs) {
      scope.myvalue = attrs.attr1;
      scope.check = function() {
          scope.message = scope.myvalue;
          console.log('scope updated with current value');
      };
      
      scope.$watch('myvalue', function(newVal){
          scope.message = newVal;
          console.log('change detected');
      });
    }
  };
});

/*
jQuery World
*/

$(function(){
  
  $("#change-dir1").click(function() {

    var domElement = document.getElementById('d1');
    var scope = angular.element(domElement).scope();  
    scope.$apply(function(){
      scope.myvalue = 1000;
      console.log('attribute changed');
    });
  });  
  
});