How propagate form submit event to parent of custom directive?

后端 未结 1 916
别那么骄傲
别那么骄傲 2021-01-20 07:03

I have a simple AngularJS project where I take input data from the user and produce a chart based on that data. I\'m trying to figure out how to organize the code so it con

相关标签:
1条回答
  • 2021-01-20 07:21

    Here is a way to do it - Plunker.

    a3j.js

    app.controller('NavigationController', function(){
      var navCtrl = this;
      navCtrl.data = null;
    });
    

    index.html

    <div ng-controller="NavigationController as navCtrl">
        <input-form data="navCtrl.data"></input-form>
        <index-chart data="navCtrl.data"></index-chart>
    </div>
    

    inputForm.js

    inputForm.directive('inputForm', function() {
        return {
          restrict: 'E',
          templateUrl: 'input-form.html',
          scope: {data: "="},
          controllerAs: 'inputCtrl',
          bindToController: true,
          controller: function() {
            var inputCtrl = this;
            inputCtrl.inputValues = {topic1Data: 123456789};
    
            inputCtrl.emitData = function() {
              inputCtrl.data =  inputCtrl.inputValues.topic1Data;
            };
          }
        };
    });
    

    input-form.html

    <form name="inputForm" ng-submit="inputForm.$valid && inputCtrl.emitData()" novalidate>
      <textarea name="topic1Data" ng-model="inputCtrl.inputValues.topic1Data" rows="10" cols="30" required></textarea>
      <button type="submit" class="btn btn-info btn-lg" ng-disabled="!inputForm.$valid">Compare</button>
    </form>
    

    indexChart.js

      indexChart.directive('indexChart', function() {
        return {
          restrict: 'E',
          templateUrl: 'index-chart.html',
          scope: {data: "="},
          controllerAs: 'chartCtrl',
          bindToController: true,
          controller: ['$scope', function($scope) {
            var chartCtrl = this;
    
            $scope.$watch('chartCtrl.data', function(newValue) {
              if (angular.isDefined(newValue)) {
                console.log(newValue);
              }
            });
          }]
        };
      });
    

    index-chart.html

    {{chartCtrl.data}}
    

    The main points to note are:

    • Each directive has an isolate scope with a data property
    • NavigationController passes the same value to these directives
    • Any change in the value can be watched and acted upon
    • Each directive is self-contained without the need for a separate controller
    • Each directive acts independently of each other
    0 讨论(0)
提交回复
热议问题