angularjs 自拍 $broadcast 和 $on

angularjs selft $broadcast and $on

我已经创建了类似于下拉菜单的自定义指令,但在我的例子中,项目在模式弹出窗口中打开,选择项目后将在 div 中选择。

现在我添加了两个指令(即同一指令的两个实例)并使用这两个指令作为父子方式。我从 rest api 中获取项目然后分配给第一个指令( 即父 )并根据第一个指令的选择我过滤另一个 rest api 然后分配给第二条指令(即 child)效果很好。但是我想在第一个指令上更改选择时重置第二个指令的值(选定项)。

我在我的指令中添加了以下代码,但它没有帮助我

controller: ['$scope', '$rootScope',
        function($scope, $rootScope) {
          $scope.$watch('value', function(val) {
            $rootScope.$broadcast('valueChanged', $scope.id);
          });
          $scope.psChanged = function() {
            $scope.$on('valueChanged', function(event, value) {
              if (value === $scope.id) {
                //Do nothing.
              } else {
                console.log("Text change");
              }
            });
          }
        }
      ]

My full working plunker http://plnkr.co/edit/f6LYS2aGrTXGkZ3vrIDD?p=preview

有人可以帮我完成吗!!

我在独立范围内又添加了一个名为 isChild 的属性,当它为真时我正在监听事件 valueChanged。所以我什至在没有函数 psChanged 的​​控制器中绑定了监听器,并且它有效。

angular.module('plexusSelect', []).directive('plexusSelect', ['$ionicModal', '$timeout', '$ionicScrollDelegate', '$rootScope',
  function($ionicModal, $timeout, $ionicScrollDelegate, $rootScope) {
    // Runs during compile
    return {
      scope: {
        'items': '=',
        'id': '@',
        'text': '@',
        'textIcon': '@',
        'headerText': '@',
        'textField': '=',
        'valueField': '@',
        'callback': '&',
        'isChild' : '@'
      },
      require: 'ngModel',
      restrict: 'E',
      templateUrl: 'plexusSelect.html',
      controller: ['$scope', '$rootScope',
        function($scope, $rootScope) {
          $scope.$watch('value', function(val) {
            $rootScope.$broadcast('valueChanged', $scope.id);
          });
          if ($scope.isChild === 'true') {
          //$scope.psChanged = function() {
            $scope.$on('valueChanged', function(event, value) {
              if ($scope.id === value) {
                //Do nothing.
              } else {
                $scope.clearSearch();
                $scope.value = '';
                $scope.text = $scope.defaultText;
                console.log("Text change");
              }
            });

          }
        }
      ],

html

<ion-view view-title="Search" ng-controller='SearchCtrl'>
    <ion-content>
    <h1>Search</h1>
  <plexus-select id="psDeparture"  is-child='false' items="deptStations" header-text="Select Departure Station" text="Select departure..." text-icon="icon-takeoff" text-field="['City_Name_EN','City_Code']" value-field="City_Code" ng-model="deptStation.value"></plexus-select>
    <plexus-select id="psArrival" is-child='true' items="arrStations" header-text="Select Arrival Station" text="Select arrival..." text-icon="icon-landing" text-field="['Destination.City_Name_EN','Destination.City_Code']" value-field="Destination.City_Code" ng-model="arrStation.value"></plexus-select>
    </ion-content>
</ion-view>

plunk