如何在两个控制器之间使用ng-change

时间:2017-12-25 12:48:21

标签: javascript angularjs

data(){
    return {
        books: []
    }
}, 
methods: {
    bsBooks: () => {
        axios
            .get(
                "..."
            )
            .then(res => {
                return this.books = res.data.results
            });
    }
},
mounted() {
    this.bsBooks();
}

<body ng-app="myApp" ng-controller="oneCtrl"> <input type="text" class="form-control" ng-model="dt" ng-change="changeDate(dt)" /> <span class="input-group-btn"> <button type="button" class="btn btn-default" ng-click="open($event)"> <i class="glyphicon glyphicon-calendar"></i> </button> </span> <div class="row" ng-controller="twoCtrl"> <!-- Here is the use of dt --> </div> </body> 发生时,我想在ng-change中使用changeDate(dt)函数的值。

1 个答案:

答案 0 :(得分:0)

在指令的帮助下我们可以做如下

HTML文件

<div ng-controller="firstController">
    {{name}} 
    <button my-directive>
      invoke function
    </button>
  <div ng-controller="secondController">
    {{name}}
  </div>

</div>

JS档案

angular.module("myApp", [])

.controller("firstController", function($scope, $rootScope){
    $scope.name = "Ctrl-1";
  var listener = $rootScope.$on("MYEVENT", function(){
    alert("IM CTRL 1");
  });

  $scope.$on("$destroy", function(){
    listener(); //de-registering event
  });

})

.controller("secondController", function($scope, $rootScope){
    $scope.name = "Ctrl-2";
  var listener = $rootScope.$on("MYEVENT", function(){
    alert("IM CTRL 2");
  });
  $scope.$on("$destroy", function(){
    listener();
  });
})

.directive("myDirective", function($rootScope){
    return{
    restrict: "AE",
    scope: {},
    link: function(scope, ele, attrs){
        ele.bind("click", function(){
        $rootScope.$broadcast("MYEVENT");
      });       
    }
  }
})