Search code examples
javascriptangularjsrootscope

Assign function from $rootScope to click event with AngularJS


How can I run this function with $rootScope ?
Fiddle

  <div ng-app="myApp" ng-controller="parentCtrl">
      {{test}}
      <div ng-controller="myCtrl1">
          <div ng-controller="myCtrl2">
              <a href="#" ng-click="value()">show me</a>     
          </div>
      </div>   
    </div>

Here are my controllers:

angular.module('myApp', []).controller('parentCtrl', function($scope, $rootScope) {
    $rootScope.test = function() {
        alert("asdasd");
    }
});

angular.module('myApp').controller('myCtrl2', function($scope, $rootScope) {
    $scope.value = $rootScope.test();
});

Alert shows up when page refresh but i want to show it after click when ng-click


Solution

  • If you want to assign the test function to $scope.value, just remove the () in the following line:

    $scope.value = $rootScope.test;
    

    See the fiddle.