使用$ emit和$ on单击按钮时显示div标签

时间:2015-11-03 13:17:37

标签: javascript html angularjs

我有两个控制器ParentController和ChildController。我想要实现的是当来自ChildController的按钮被点击以发出事件并在ParentController中监听该事件并且单击按钮以在div标签中显示iframe时。你可以在下面找到我的代码。

ParentController

var myApp = angular.module("myApp", []);

myApp.controller('ParentController', ['$scope', function ($scope) {   

}]);

* ChildController **

myApp.controller('ChildController', ['$scope', function ($scope) {

}]);

查看ParentController

<div ng-controller="ParentController">
  <div class="module-content">
     <h3>Title</h3>
  </div>
  <div content-body>
      <div ng-show="$on('showiframe')">
         <iframe ng-src={{url}} frameborder="0"></iframe>
      </div>
  </div>
<div>

查看ChildController                            显示IFrame         
      

我可以做这样的事情,在ng-show中听div标签中的事件吗?

1 个答案:

答案 0 :(得分:2)

在您的ChildController中,$会在您点击按钮时发出一个事件。 $ emit将通过范围层次结构向上调度事件。

儿童观点:

<button type="button" ng-click="showIframe()">Show iframe</button>

儿童控制器:

myApp.controller('ChildController', ['$scope', function ($scope) {
    $scope.showIframe = function () {
        $scope.$emit('showiframe');
    }
}]);

在父控制器中,在'showIframe'事件上创建一个监听器。

家长观点:

<div ng-controller="ParentController">
  <div class="module-content">
     <h3>Title</h3>
  </div>
  <div content-body>
      <div ng-show="showIframe">
         <iframe ng-src={{url}} frameborder="0"></iframe>
      </div>
  </div>
<div>

家长控制器:

var myApp = angular.module("myApp", []);

myApp.controller('ParentController', ['$scope', function ($scope) {
     // Iframe is not showed initially     
     $scope.showIframe = false;   

     $scope.$on('showIframe', function() {
          $scope.showIframe = true;
     });
}]);

编辑:

关于你的小提琴,例如,你可以观看inputText模型并发出事件:

$scope.$watch('inputText', function () {
        $scope.$emit('send-date', $scope.date);
        $scope.$emit('send-input', $scope.inputText);
});

每次inputText模型更改时,这将发出事件。