Angular - updating a scope variable in a controller function call is not reflected in the html directive

I played with angular, trying to understand how it manages areas, then I found that I could not update the variables in the directive using a function call.

To illustrate this problem, here is my simple application: The idea is that when you click the switch link, the menu should appear, and when you click it again or somewhere else, the menu should disappear.

angular.module('app', [])
  .controller('DemoController', ['$scope', function($scope) {

  }])
  .directive('dropdown', function() {
    return {
      restrict: 'E',
      transclude: true,
      controller: function($scope) {
        $scope.onBlur = function () {
          // this doesn't actually work
          $scope.showMenu = false;
        };
      },
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body id="body" ng-app="app" ng-controller="DemoController">
  <dropdown ng-transclude>
    <a href="#" ng-click="showMenu = !showMenu" ng-blur="onBlur()">Toggle</a>
    <menu ng-show="showMenu">
      <div>I'm</div>
      <div>the drop-down</div>
      <div>menu</div>
    </menu>
  </dropdown>
</body>
Run codeHide result

Here are my plunker links:

Non-working version: http://plnkr.co/edit/rfdt5FEoGAOX15RZUsKA?p=preview

Working version: http://plnkr.co/edit/xMANGDVa8n64OKK3gOgg?p=preview

, ng-blur="showMenu = false" . $scope.$apply() , "$ apply is is progress".

, - , , . .

+4
1

$scope. $apply() , $scope. $$ phase (, $digest $apply phase)

if (!$scope.$$phase) {
   $scope.$apply()
}

:

$scope.showMenu = false;
to 
this.showMenu = false;

$scope.

+2

All Articles