I\'m looking for a way to get initial data from a DOM after the application is loaded. Data has been inserted in a view by a server. Is Module\'s value
1) First solution inspired by this question and it is Module's value method:
- {{user.name}}
Then we can use this PrimaryData when and where we wish , like this:
myApp.controller('MainCtrl', function($scope, PrimaryData) {
$scope.data = angular.copy(PrimaryData);
console.log( $scope.data[0].name === "John" );
});
But this way somehow not worked for me when i started to use routes , may be because the value only runs while application initialization.
2) So here comes the second solution: directives. Now when server sends a route's template , it puts inside some script tag with a "text/template" type and special directive name property and a json data in that tag, like this:
- {{user.name}}
// view is beside
And this directive catching it and passes the data to the current route' scope:
studio.directive('rawdata', function() {
return {
link: function(scope, element, attr, ctrl) {
if(scope.passRawData){
var data = (element[0].innerHTML);
scope.passRawData(data); // Or simply scope.users = JSON.parse(data)
} else {
console.log( "Scope has no passRawData method" );
}
}
}
});
Awesome! :)