yarek
yarek

Reputation: 12064

angularjs: how to call a function without scope?

Here is my model

<html ng-app="myApp">
    <button id="rainBtn" ng-click="makeItRain()">Make it rain !  </button>      
    <div class="tab-pane active" id="lobbyTab" ng-controller="chatController"></div>

And here is my myApp.js

var myApp = angular.module('myApp',[]);
makeItRain = function() {
    alert("ok");
}

makeItRain is never called:

How to call the makeItRain() function ?

Upvotes: 1

Views: 1359

Answers (2)

ryeballar
ryeballar

Reputation: 30118

You can't get a reference from a global function as an angular expression. One possible way to do this without using a controller is to use $rootScope and attach the function during the .run() phase, although it is not recommended:

myApp.run(function($rootScope) {

  $rootScope.makeItRain = function() {
     alert('Raining!');
  };

});

Another way is to abandon the idea of attaching an event handler via ng-click directive and simply create a directive. This solution assumes that the event handler you are trying to attach will perform dom manipulations.

myApp.directive('makeItRain', function() {
  return function(scope, elem, attr) {
    elem.on('click', function() {
      makeItRain();
    });
  };
});

and then attach it in the HTML:

<button id="rainBtn" make-it-rain>Make it rain !  </button>

Upvotes: 1

rnrneverdies
rnrneverdies

Reputation: 15667

Make a Controller

var myApp = angular.module('myApp',[]);

myApp.controller("sky", ["$scope", function($scope) {
    $scope.makeItRain = function() {
       alert("ok");
    }
}]);

Set the controller

<button id="rainBtn" ng-controller="sky" ng-click="makeItRain()">

Upvotes: 3

Related Questions