$watch vs $observe

by Samar Pattanayak

HTML

<div ng-app="myApp">
  <div ng-controller="myController">
    {{url}} stays at {{myHome}} --> from controller
    <input type="text" ng-model="myHome"/>
    <div ng-model="hello" tab first="url" second={{myHome}} attr1="fcuk" attr2="23" attr3={{v3}} id="divTab">

    </div>
  </div>
</div>

JavaScript

var app = angular.module("myApp", []);
app.controller("myController", function($scope, $location) {
  $scope.url = "samar"
  $scope.myHome = "balasore"
  $scope.v3 = "Bangalore"
    //$scope.fcuk= "hello from here"
    //will take as string in html
})
app.directive("tab", function($interpolate) {
  return {
    restrict: "EA",
    scope: {
      first: "=",
      second: "@"
    },
    require: 'ngModel',
   // compile: function(tele, tattr) {
      //in compile {{}} and two way binding variables will not be evaluated(oneway binding or direct)
      //console.log(tattr.attr1 + tattr.first + tattr.second + tattr.attr2 + tattr.attr3)
      //return {
        link: function(scope, ele, attr, ctrl) {

          //in link 'attr.fisrt' variable will not be evaluated
          console.log(attr.attr1 + $interpolate(attr.first)(scope) + attr.second + attr.attr2 + attr.attr3)

          //$watch works with interpolated string if its having one way binding with @
          //first , it will evaluate
          //second , it will  evaluate(one way binding with @ <<---->>interpolated string)
          //attr3 , it will not evaluate
          scope.$watch("second", function(nv, ov) {
            console.log("changes in $watch " + nv)
          })

          //$observe always works for interpolated string and rest else works with $watch
          //first , it will not evaluate
          //second , it will evaluate(interpolated string)
          //attr3 , it will  evaluate(interpolated string)
          
          attr.$observe("second", function(value) {
              console.log("changes in $observe " + value)
                //alert("hi")
            })
            //console.log(ele.html())
        },
      //}
    //},
    template: "<div><input type='text' id='idfirst' ng-model='first'/><div>You are changing {{first}} and he stays at <input type='text' ng-model='second' id='idsecond'/><input type='button' id='btnDirec' value='Change Here'...