scope.$on('$destroy', function() {
elem.tooltip('destroy');
}
function FooCtrl($rootScope) {
this.someMethod = function() {
// some code ...
if (someCondition) {
$rootScope.$emit('someEvent');
}
}
}
function BarCtrl($scope, $rootScope) {
var deregFn = $rootScope.$on('someEvent', function() {
// some code ..
};
$scope.$on('$destroy', function() {
deregFn();
});
}
<script>
window.$$userData = <?= json_encode($_SESSION['user']); ?>;
</script>
<script src="/path/to/angular.js"></script>
<script src="/path/to/app.js"></script>
app.config(['$provide', function($provide) {
$provide.constant('userData', angular.copy(window.$$userData));
}]);
app.service('Foo', function($q, $http) {
// Promise cache
var cache = {};
// Consider we've some url
var API_URL = '/api/v1/';
/**
* Get friends data
*/
this.getFriendsData = function() {
return apiCall('getFriendsData');
};
/**
* Get upcoming events
*/
this.getUpcomingEvents = function() {
return apiCall('getUpcomingEvents', {since: Date.now()});
};
function apiCall(method, params) {
// Check internal cache
if (!cache[method]) {
// Create new deferred for method
var deferred = $q.defer();
cache[method] = deferred.promise;
// Merge params
// e.g. some tokens/keys may exist in default params
var data = {params: angular.extend({}, params)};
// Process request
$http.get(API_URL + method, data).then(function(response) {
deferred.resolve(response);
});
}
return cache[method];
}
});
app.controller('FirstCtrl', function(Foo) {
// viewmodel reference
var vm = this;
Foo.getFriendsData().then(function(friendsData) {
vm.friendsData = friendsData;
});
});
app.controller('SecondCtrl', function(Foo) {
// viewmodel reference
var vm = this;
Foo.getUpcomingEvents().then(function(upcomingEvents) {
vm.upcomingEvents = upcomingEvents;
});
Foo.getFriendsData().then(function(friendsData) {
// $http.get won't be called, getting data from promise cache
vm.friendsData = friendsData;
});
});