How propagate form submit event to parent of custom directive?

后端 未结 1 915
别那么骄傲
别那么骄傲 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

    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

    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)
提交回复
热议问题