It is advisable to fetch your data from a dedicated service:
app.factory('myService', function($http) {
var fetchedData = [];
return {
getData: function() {
var promise = $http({method:'GET', url:'/api/someurl' });
promise.success(function(data) {
angular.copy(data, fetchedData);
});
return promise;
},
data: fetchedData
}
});
Next, assign the retrieved data to your current scope within your controller
app.controller('ctrl', function($scope, myService) {
$scope.data = myService.data;
});
Display the data in your HTML, or utilize it inside your directive
<body ng-app="app">
<ul>
<li ng-repeat="item in data">{{ item }}</li>
</ul>
<my-directive model="data"></my-directive>
</body>
If you opt for a custom directive, make sure to set up your $watch function in the link function of your directive:
app.directive('myDirective', function() {
return {
restrict: 'E',
link: function(scope, elem, attr) {
scope.$watch('data', function(newVal) {
...
});
}
}
});
Keep in mind that $watch handlers should not be part of a promise's callback. It is best to keep them separate to maintain a clear distinction between data retrieval and consumption.