Pass and then parse real code from JSON in Angular.js

Question!

So... Hey everyone, v'got another question... Currently I am building own website-blog (from scratch for the purpose of self-education) that will contain some funny staff and some smart stuff (like articles with my code), now it's just a static site that works due to Angular.js. One day it will be dynamic with RoR at backend, but, never mind, now about issue that I have faced yesterday. For example: I've got route for all 'smart' posts looks like:

.state('smartStuff', {
  url: '/smartStuff',
  views: {
    'content': {
      templateUrl: 'html/smartStuff.html',
      controller: 'SmartStuffController'
    }
  }
})

Then, single post's page create dynamically:

.state('postsAboutSmartStuff', {
  url: '/smartStuff/{smartStuffPostId}',
  views: {
    'content': {
      templateUrl: 'html/post.html',
      controller: 'SmartStuffController'
    }
  }
})

Content that I represent in each post I get from JSON via service...

angular.module('postsServices', [])
.factory('postsFactory', function($http) {
    var promise;
    return {
        all: function() {
            if(!promise) {
                promise = $http.get('postsSmartStuff.json')
                    .then(function(response) {
                        return response.data;
                    })
            }
            return promise;
        }
    }
});

and then controller... like:

var postsControllers = angular.module('postsControllers', []);
postsControllers.controller('SmartStuffController', function($scope, postsFactory, $stateParams) {
  postsFactory.all()
      .then(function(posts) {
          $scope.posts = posts;
          $scope.smartStuffPostId = $stateParams.smartStuffPostId;

          function getById(arr, id) {
             for (var i = 0; i < arr.length; i++) {
                  if (arr[i].id == id) {
                      return arr[i];
                  }
             }
          }
          $scope.singlePost = getById($scope.posts, $stateParams.smartStuffPostId);

      });
}); 

ALL WORKS FINE! When my JSON looks like:

[{
    "id": 1,
    "theme": "vanilla javascript",
    "title": "Post 2",
    "description": "Description two"
 },
 {...}, 
]

I mean when I 'give' my JSON just TEXT. But as I have already mentioned - I want and will write some actual code in my articles... So, at last, my question - How can I pass any real code and then correctly parse in Angular's controller? I feel that it's very bad practice to pass code(functions, wateva) like this, but now I do not see other solutions. I'm just learning so sorry anyway and any decent help will be greatly appreciated. Hope I make myself absolutely clear :)



Answers

The easiest way to do this is to actually store your text as Markdown, and then use a markdown directive such as this one: https://github.com/btford/angular-markdown-directive to display all your text.

/* UPDATE */ To be clear, what I meant was that your content should be in Markdown. So each post would still be some kind of JSON object, but whatever data element you're using to represent the body of your post (not clear from above) or any other part of the post that should have formatted content should be in Markdown, and then passed to an Angular directive that can transform that Markdown into HTML.

So for example, you might have a JSON object like:

{
    "id": 1,
    "theme": "vanilla javascript",
    "title": "Post 2",
    "description": "Description two",
    "content" : "Hey, I have some awesome content here: ```var t = 'awesome'; alert(t); ```"
 }

Then you fetch it like you already do, but when you instantiate the angular-markdown-directive, you'd bind that directive to your content:

<!-- Assuming 'content' is in the current scope; might have to be singlePost.content or something else --> 
<div btf-markdown="content">
</div>

or possibly:

<btf-markdown>{{singlePost.content}}</btf-markdown>
By : Paul


You can easily do this with numpy by sorting both lists (to get a mapping between the two lists) and by inverting one of the sorting permutations:

import numpy as np

a = [7, 14, 0, 9, 19, 9]
b = [45, 42, 0, 1, -1, 0]

a = np.array(a)
b = np.array(b)

ai = np.argsort(a)
bi = np.argsort(b)
aiinv = np.empty(ai.shape,dtype=int)
aiinv[ai] = np.arange(a.size)  # inverse of ai permutation

b_new = b[bi[aiinv]]
# array([ 0, 42, -1,  0, 45,  1])

numpy.argsort gives the indices (permutation) that will sort your array. This needs to be inverted to be used inside b, which can be done by the inverted assignment

aiinv[ai] = np.arange(a.size)


I don't think you'd be able to handle this with just Eloquent but it can get you very close... You could use methods on the Collection to get you the rest of the way.

$users = App\User::with('stats')->get();
$sortedUsers = $users->sortByDesc(function($user) {
    return $user->stats->count();
});


This video can help you solving your question :)
By: admin