Last active
December 14, 2015 00:29
-
-
Save davisford/4999474 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}]); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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