Skip to content

Instantly share code, notes, and snippets.

@Micka33
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Micka33/a8481c4acb4f229df21e to your computer and use it in GitHub Desktop.
Save Micka33/a8481c4acb4f229df21e to your computer and use it in GitHub Desktop.
An AngularJS module that load raw json datas from the html on load

#Why rawData (reminder)

Because I don't want to have two requests to load one page (one for the squeleton, one for the datas).
So I want to embed the datas in my page on the first request to load them directly.

#How to use rawData

<div>
  <p>{{the_datas}}</p>
  <script ng-bind='the_datas' raw-data='json'>{"stuff":23,"other":"data"}</script>
</div>
<div>
  <p>{{the_datas}}</p>
  <script initdata='{"stuff":23,"other":"data"}' ng-bind='the_datas' raw-data='json'></script>
</div>

What can be added

more if can be added to be able to load strings/integers/booleans.

...
try{
  if ($attrs.rawData.toLowerCase() == 'json')
    $scope[$attrs.ngBind] = angular.fromJson(text);
...
(function(window, angular, undefined) {'use strict';
angular.module('loadRawData', [])
.directive('rawData', ['$log', function($log) {
return {
restrict: 'A',
link: function ($scope, $element, $attrs)
{
if ( typeof $attrs.ngBind !== 'undefined')
{
var text = ($attrs.initdata ? $attrs.initdata : $element.text());
try{
if ($attrs.rawData.toLowerCase() == 'json')
$scope[$attrs.ngBind] = angular.fromJson(text);
}catch(e){
$log.error(e);
$log.info('you sent:', text);
$log.info('raw-data was expecting:', $attrs.rawData);
}
}
}
}
}]);
})(window, window.angular);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment