title: AngularJS watching service variable from directive, how to correctly implement factory?
body: <p>I want to watch angular factory variable from inside directive, and act upon change.  </p>
  
  <p>I must be missing something fundamental from Javascript, but can someone explain, why approach (1) using inline object works, and approach (2) using prototyping does not?  </p>
  
  <p>Does prototype somehow hide <code>user</code> variable scope from angular $watch?  </p>
  
  <p>How can i make this code more clean?</p>
  
  <p>(1):<br>
  <a href="http://plnkr.co/edit/2cjA6GMFX1Cp5NYAkN35?p=preview" rel="nofollow">Plunkr demo</a></p>
  
  <pre><code> angular.module('testApp', [
        ])
        .factory('myUser', [function () {
           var userService = {};
           var user = {id : Date.now()};
           userService.get = function() {
             return user;
           };
           userService.set = function(newUser) {
             user = newUser;
           };
          return userService;
        }])
        .directive('userId',['myUser',function(myUser) {
          return {
            restrict : 'A',
            link: function(scope, elm, attrs) {
              scope.$watch(myUser.get, function(newUser) {
                if(newUser) {
                  elm.text(newUser.id);
                }
              });
            }
          };
        }])
        .controller('ChangeCtrl', ['myUser', '$scope',function(myUser, $scope) {
          $scope.change = function() {
            myUser.set({id: Date.now()});
          };
        }]);
  </code></pre>
  
  <p>(2):<br>
  <a href="http://plnkr.co/edit/MEis5MMN9BLXxrmy58cF?p=preview" rel="nofollow">Plunkr demo</a></p>
  
  <pre><code> angular.module('testApp', [
        ])
        .factory('myUser', [function () {
  
           var user = {id : Date.now()};
           var UserService = function(initial) {
              this.user = initial;
           }
           UserService.prototype.get = function() {
             return this.user;
           };
           UserService.prototype.set = function(newUser) {
             this.user = newUser;
           };
          return new UserService(user);
        }])
        .directive('userId',['myUser',function(myUser) {
          return {
            restrict : 'A',
            link: function(scope, elm, attrs) {
              scope.$watch(myUser.get, function(newUser) {
                //this watch does not fire
                if(newUser) {
                  elm.text(newUser.id);
                }
              });
            }
          };
        }])
        .controller('ChangeCtrl', ['myUser', '$scope',function(myUser, $scope) {
          $scope.change = function() {
            myUser.set({id: Date.now()});
          };
        }]);
  </code></pre>