在指令中观看ng-show是相反的

时间:2016-08-01 07:48:55

标签: javascript angularjs

当我的指示被显示或隐藏时,我试图做一些逻辑。但正如您在此fiddle中所看到的,报告元素的可见性是错误的。

我在这里想念什么?

HTML:

<div ng-app='app'>
  <div ng-controller='testController'>
    <dialog ng-show='showDialog'>
      <p>
        I'm a dialog
      </p>
    </dialog>
    <button ng-click='showHideDialog()'>
      Show/Hide
    </button>
  </div>
</div>

Angular js:

var app = angular.module('app', []);
app.directive('dialog', function() {
  return {
    restrict: 'E',
    replace: true,
    transclude: true,
    scope: false,
    template: '<div class="dialog">' +
      '<div class="overlay"></div>' +
      '<div class="body" ng-transclude>' +

      '</div>' +
      '</div>',
    link: function(scope, element, attributes) {
      scope.$watch(function() {
        return element.is(':visible')
      }, function() {
        dialog = element;
        console.log('visibility of dialog changed to ', element.is(':visible'));
      });
    }
  };
});
app.controller('testController', function($scope) {
  $scope.showHideDialog = function() {
    $scope.showDialog = !$scope.showDialog;
  };
});

1 个答案:

答案 0 :(得分:0)

我已在directive方更新了您的代码,包括directive ngShow范围对象。更新了您的加扰scope.$watch后,请观看ngShow值以进行更改。

查看

<div ng-app='app'>
  <div ng-controller='testController'>
    <dialog ng-show='showDialog'>
      <p>
        I'm a dialog
      </p>
    </dialog>
    <button ng-click='showHideDialog()'>
      Show/Hide
    </button>
  </div>
</div>

CONTROLLER&amp; DIRECTIVE

var app = angular.module('app', []);
app.directive('dialog', function() {
  return {
    restrict: 'E',
    replace: true,
    transclude: true,
    scope: {
        ngShow:'='
    },
    template: '<div class="dialog">' +
      '<div class="overlay"></div>' +
      '<div class="body" ng-transclude>' +

      '</div>' +
      '</div>',
    link: function(scope, element, attributes) {
      scope.$watch('ngShow',function() {
        console.log('visibility of dialog changed to ', element.is(':visible'));
      }, function() {
        console.log('visibility of dialog changed to ', element.is(':visible'));
      });
    }
  };
});
app.controller('testController', function($scope) {
  $scope.showHideDialog = function() {
    $scope.showDialog = !$scope.showDialog;
  };
});

JSFIddle