javascript – Consume Angular REST Service – Return JSON


I have the following function in angular that consumes a service:

function GetDados($scope, $http) {
        $scope.dados = data;

I need $ to go to this place

<div ng-controller="GetDados">
        var json = $scope.dados; 

Does not work. I don't know if this is allowed.

What I have in data is a json with multiple records. The error it shows me is that it doesn't recognize the variable $scope. Thanks.


function GetDados($scope, $http){
    //$scope.dados = data;

            var json = data; 

My goal was to build a chart using service feedback. I put the graphic script in the same service call and used it. The ng-bind that the colleague mentioned helped too.


This happens because for you to pass the result of an Angular controller to the view (html) you need to bind . This is done in 2 ways:

  • <p>{{ nomeDoScope }}</p>
  • <p ng-bind="nomeDoScope"></p>

So, assuming you have a $scope like $scope.nomeDoScope = 'Meu teste' , the value that would be displayed on the screen would just be "My Test", that is, in your case the JSON would be displayed.

Remembering that it doesn't need to be inside a p tag, it can be in any element, as long as it follows that pattern.

In your example it would be: {{dados}}

When to use one or the other?

There is controversy and even speculation about the performance of using {{}} or using the ngBind directive. In fact there is a performance difference ( ngBind is better), however very minimal, it will only have an impact when used on a large scale, and I say REALLY BIG SCALE ! In most cases they don't.


So, considering a scenario where you have many bindings, especially within a large text, the ideal would be to use the ngBind directive. Imagine that you have a p element that generates a text of 2 thousand lines, when using the {{}} method the analysis scope is not defined, so the validation will go through the entire text until it finds the bind and thus apply it. When using ngBind, the scope is defined and covers only the piece of text that must be updated, so the performance is better.


<p>Aqui inicia nosso texto de exemplo muito...
    [..muito texto..] 
    <span ng-bind="meuEscopo"></span> e aqui continua nosso texto extenso...
    [...muito texto...]

{{ }}

It is used in most cases. Why? Simplicity. Imagine having to create a span element just to place a piece of text? Boring right? Yeah. That's why in most cases the use of {{}} is preferred, and as said above, the difference in performance is not so significant.

If you have a title element that will only be used to display the title, it costs nothing to use ngBind , example: <h6 ng-bind="meuEscopo"></h6> .


<p>Aqui temos um exemplo curto com {{meuEscopo}} e aqui ele finaliza</p>

But there is no need to do this just for a single element.

I think this makes it clearer for you to understand.

Scroll to Top