当按钮被点击时使用$emit和$on展示div标签

3
我有两个控制器:ParentController和ChildController。我想要实现的是,当从ChildController的按钮被点击时发出事件并在ParentController中监听该事件,并在按钮被点击时显示iframe在div标记中。您可以在下面找到我的代码。
ParentController
var myApp = angular.module("myApp", []);

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

}]);

*ChildController**

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

}]);

家长控制器的视图
<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个回答

2
在您的ChildController中,当按钮被点击时,请使用$emit触发一个事件。$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;
     });
}]);

编辑:

关于你的fiddle,例如,你可以观察inputText模型并发出事件:

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

每次inputText模型发生变化时,都会触发这些事件。

谢谢@Komo。你能看一下这个fiddle http://jsfiddle.net/bF9Pq/695/ 来回答我的另一个问题吗?我在ChildController中有输入文本和日期输入。我想要实现的是从这些输入中获取值并将它们传递给监听这些值的ParentController。对于日期输入,我想要将默认值设置为Date.now(),如果我选择了其他日期,则将该值发送到ParentController。 - Micko
在你的fiddle中,你在控制器初始化时只发出了send-date和send-input事件。你需要一个动作(例如按钮点击)(或$watch),在其中触发$emit。看一下我的编辑。 - Komo
非常感谢你,我的朋友!!!现在我有点困惑,为什么我不能从MainController中的这两个函数中获取$scope.startDate和$scope.getInputText的值...我在开头定义它们$scope.startDate = null; $scope.getInputText = null;然后在$on函数中赋值? - Micko
你说的“no taking the value”是什么意思? 尝试在输入框中输入一些内容:http://jsfiddle.net/bF9Pq/696/ - Komo
不是,这个是使用watch在工作。我是说你可以看到我有两个console.log($scope.startDate)和console.log($scope.getInputText),它们在我监听的函数之外。所以我想在函数中获取这些值,例如在MainController的其他函数中。 - Micko
你一旦触发了这些事件,就可以访问这些$scope变量。 - Komo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接