Skip to content

Instantly share code, notes, and snippets.

@davisford
Last active December 14, 2015 00:29
Show Gist options
  • Save davisford/4999474 to your computer and use it in GitHub Desktop.
Save davisford/4999474 to your computer and use it in GitHub Desktop.
var app = angular.module('app', []);
// service to fetch data
app.factory('Service', ['$rootScope', function ($rootScope) {
var Data = {}, intervalId;
return {
data: Data,
get: function () {
// code will fetch and populate Data
},
// function to continuously update data
start: function () {
intervalId = setInterval(function () {
$rootScope.$apply(function () {
// modifies Data object
});
}, 1000);
}
}
}]);
// directive to update dom whenever bound data changes
app.directive('fooBar', [function () {
return {
restrict: 'E',
scope: {
val: '='
},
link: function (scope, element, attrs) {
// watch val attribute and update dom whenever it changes
scope.$watch('val', function (newVal, oldVal) {
// code to update dom
});
}
};
}]);
// controller
app.controller('AppCtrl', ['$scope, Service', function ($scope, Service) {
// bind scope data to Service
$scope.data = Service.data;
// fetch data one time
Service.get();
// start continuous data fetch
Service.start();
}]);
<!DOCTYPE html>
<html ng-app="app">
</html>
<body ng-controller="AppCtrl">
<!-- bind val in directive to $scope.data -->
<foo-bar val="data" />
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment