2

This is just for test and learn. I am having a JSON object obj. I want to call angular Json filter on that to format that json object and print it on chrome console. Not by any button click. Just by writing code in directly on console of chrome.

I know I can that with some online tool or offline tool as well. But I want to learn how to run a angular defined filter in a plain JavaScript.

Note:

  • I can call it in view like {{obj | Json}}
  • I can also call it from controller as $filter('Json')(obj);

But I am not able to call it in pure javascript where angular is appended with script tag but not bootstrapped (started). I am able to access angular object though.

I want something like

var $filter = angular.filter(); //Since I do not have controller here
console.log($filter('Json')(obj));
4
  • To understand more this problem, Suppose you just want to use filter of angular neither controller nor any other thing of angular. Then you will want to call filter directly from your plain JavaScript code. This is what I want to know. It is silly I know, But it could grow our knowledge as hacking angular to use it as pertials ;) Commented Feb 3, 2016 at 5:53
  • 1
    You need to bootstrap angular to access it, but you could set a global variable and assign it $filter in an app so you could test in console if that's what you want Commented Feb 3, 2016 at 6:02
  • Ok thats great. If I asign the filter object to my gobal variable. I understand it now. But come to the first point. How to botstrap and only use filter? Commented Feb 3, 2016 at 6:05
  • If you just want to test things.... do it in plunker. Can set up a new app in 15 seconds. Angular isn't a library...it's a framework Commented Feb 3, 2016 at 6:10

1 Answer 1

3

var $injector = angular.injector(['ng']);
var $filter = $injector.get("$filter");
var obj = {a:1};
console.log($filter("json")(obj));
<script src="//unpkg.com/angular/angular.js"></script>

The DEMO on JSFiddle.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. This is what I was looking for. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.