1

I have a main js file which has watch in the controller -

(function () {
    'use strict';

    angular
        .module('mainmodule')
        .controller('file1Ctrl', file1Ctrl);

    
    file1Ctrl.$inject = ['$scope','data'];
    function VendorDetailCtrl($scope,data){
    var vd = this;
    vd.data.id = data.id;
    activate();
    
    function activate() {
      $scope.$watch("vd.data.id", function (newValue, oldValue) {

                        if (newValue !== oldValue) {
                            callmainfunction();
                        }

                    });
    }
    })();
    

And then I have another directive in another js file -

(function () {
    'use strict';

    angular
        .module('mainmodule')
        .directive('file2', file2)

    function file2() {
        var directive = {
            restrict: 'E',
            templateUrl: 'file2.html',
            scope: {
                data: '=',
            },
            
            controller: ['$scope',file2Ctrl],
            controllerAs: 'vm',
            bindToController: true
        }

        return directive;
        function file2Ctrl($scope, file2Ctrl) {
            var vm = this;
            activate();
            
            function activate(){
            neededfunc();
            }
            
            function neededfunc(){
            //do something
            }
      })();

I need to call the neededfunc() in the watch in first js file. I even tried adding watch in the directive but it only triggers on page reload and I need it to run after a button click Submit(). The watch is triggered when I click the button Submit(). So I needed to know how can I use the function in the watch or is there any other way I can call the function when the id value is changed.

assembler
  • 3,098
  • 12
  • 43
  • 84
Ankur Rai
  • 297
  • 1
  • 5
  • 19

1 Answers1

0

Adding function to $scope.$root helped. Following is the code -

// Declare the function

$scope.$root.neededFunction = function(){
//Do Something here
}


//Call the function

$scope.$root.neededFunction();
Ankur Rai
  • 297
  • 1
  • 5
  • 19
  • And how do you do it if you reference multiple time the said directive in the same page ? If you want to know how to do, you should present the functionnality you're trying to achieve and we may be able to tell you how to do it differently. A common way to communicate between components is to use the event system, using `$broadcast`.check https://stackoverflow.com/questions/19446755/on-and-broadcast-in-angular – Walfrat Nov 15 '17 at 15:16