如果模型属性更改,则触发$ emit事件

时间:2018-03-06 11:43:59

标签: angularjs

我正在尝试使用$emit + $on将一些数据从子控制器传递到父控制器。

这是我的代码。

angular.module('myApp', [])
    .controller('parentCtrl', ['$scope', '$http', '$q', function ($scope, $http, $q) {
        $scope.message = 'parent';

        $scope.$on('EventFromChild', function (event, data) { 
          console.log("Event Received");
          $scope.message = data;
        });        
    }])
    .controller('childCtrl', ['$scope', '$http', function ($scope, $http) {
        $scope.data ={"name":"Amit","lastname":"kumar"};
        $scope.$emit('EventFromChild',$scope.data.name);
        $scope.update = function(){
          console.log("Clicked");
          $scope.data.name ="Testing";
        };
    }]);

当加载页面然后,然后它成功地将数据从子项传递给父项,但是当我更新子项中的数据时,我还希望它反映在父控制器中,但它没有发出这个事件。

Plunker

1 个答案:

答案 0 :(得分:0)

这是因为孩子更新后你什么也没做。

您必须使用$watch来观察更改。例如,如果您希望在except更改时发出更改:

data.name

或当 $scope.$watch('data.name', function() { $scope.$emit('EventFromChild',$scope.data.name); }); 的任何属性发生变化时:

data

这样来了:

    $scope.$watch('data', function() {
      $scope.$emit('EventFromChild',$scope.data);
    });

<强>段:

angular.module('app.controllers', [])
  .controller('parentCtrl', ['$scope', '$http', '$q', function ($scope, $http, $q) {
      $scope.message = 'parent';

      $scope.$on('EventFromChild', function (event, data) { 
        console.log("Event Received");
        $scope.message = data;
      });        
  }])
  .controller('childCtrl', ['$scope', '$http', function ($scope, $http) {
      $scope.data ={"name":"Amit","lastname":"kumar"};
      $scope.$emit('EventFromChild',$scope.data.name);
      $scope.update = function(){
        console.log("Clicked");
        $scope.data.name ="Testing";
      };
      $scope.$watch('data.name', function() {
        $scope.$emit('EventFromChild', $scope.data.name);
      });
  }]);
// Code goes here
mc = angular.module('app', [
  'app.controllers',
]);

angular.module('app.controllers', [])
    .controller('parentCtrl', ['$scope', '$http', '$q', function ($scope, $http, $q) {
        $scope.message = 'parent';
       
        $scope.$on('EventFromChild', function (event, data) { 
          console.log("Event Received");
          $scope.message = data;
        });        
    }])
    .controller('childCtrl', ['$scope', '$http', function ($scope, $http) {
        $scope.data ={"name":"Amit","lastname":"kumar"};
        $scope.update = function(){
          console.log("Clicked");
          $scope.data.name ="Testing";
        };
        $scope.$watch('data.name', function() {
          $scope.$emit('EventFromChild',$scope.data.name);
        });
    }]);