uday s
uday s

Reputation: 63

$Watch not working while watch text scope variable from the controller

$Watch not working while watch text scope variable from the controller. But scope is available for function call like "ng-blur", why not for $watch. What is wrong with my flow. Can anyone give suggestion

Html

<div ng-include="'html/bar.html'" ng-controller="barController"></div>
<div class="content-container view" data-ui-view>
    </div>

bar.html

<li data-ng-repeat="menu in menuData.menus" data-ng-init="menu.showSubMenu = false">
        <a class="main-menu" data-ng-click="menu.showSubMenu = !menu.showSubMenu">{{menu.menuName}}</a>
          <div data-ng-show="menu.showSubMenu && menu.subMenus" class="top-nav-menu-wrapper" style="display: block;">
              <div class="menu-container">
                <div class="drop-down-menu" style="display: block; top:10px;">
                  <div class="container-left" data-equalizer="">
                    <ul>
Menus li
</ul></div></div></div></div></li>

barController

$scope.$watch('menu.showSubMenu', function(newValue, oldValue) {
 console.log(newValue);
 if (newValue !== oldValue) {
  // stuff
 }
});

also tried this
$scope.$watchCollection('menu', function(newValue, oldValue) {
 console.log(newValue);
 if (newValue !== oldValue) {
  // stuff
 }
});

I gave context html only for understand scenario. here I need to access "menu.showSubMenu" variable from controller also update from controller while click on window to close sub menu

Upvotes: 0

Views: 63

Answers (1)

uday s
uday s

Reputation: 63

I tried this and working fine

(function () {
"use strict";
define([], function () {
    return ['constantService', '$timeout', '$window', '$rootScope', function (constantService, $timeout, $window, $rootScope) {
        return {
                restrict: 'EA',
                scope: false,
                link: function(scope, element, attr) {
                  var w = angular.element($window);
                  var tempScope = '';
                  console.log(scope.$parent.menu);
                  scope.$parent.$watch('menu.showSubMenu', function(newValue, oldValue, scope) {
                    console.log(newValue);
                    if (newValue !== oldValue) {
                      tempScope = scope;
                    }
                  });
                  w.bind('click', function(event){
                    var currentEle = $(event.target);
                    //$rootScope.$broadcast('dropdown:close');
                    if(tempScope.menu && !(currentEle.hasClass('main-menu'))) {
                      console.log(tempScope);
                      tempScope.menu.showSubMenu=false;
                      tempScope.$apply();
                    }
                  });
                }
            };
    }];
});
}());

Upvotes: 0

Related Questions