JC Borlagdan
JC Borlagdan

Reputation: 3638

How to properly apply Angularjs ng-repeat?

I'm just a beginner in angularjs, and I'm creating an app, I already made the output correctly but I want to achieve it without using jQuery, I want to do it using angularjs way using "ng-repeat".

The following code is what's inside my controller:

.controller('SomeListCtrl',function(SomeFromService, $scope, $stateParams, $http){

var encodedString = 'action=' + 
        encodeURIComponent("getSomething") +
        '&count=' +
        encodeURIComponent("10") + 
        '&page=' +
        encodeURIComponent("1");

$http({
    method: 'POST',
    url: 'http://service.something/site.aspx',
    data: encodedString,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
    $scope.myData = data;
})
.error(function(data, status){
    console.log(status);
})
})

And this is in my html where I need to pass it:

<ion-view view-title="Latest News">
  <ion-content>
    <ion-list>
      <ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="data as myData" type="item-text-wrap" href="#/tab/myLink/{{data.id}}">
        <img ng-src="http://the-v.net{{data.ImageLink}}">
        <h2>{{data.localTitle}}</h2>
        <i class="icon ion-chevron-right icon-accessory"></i>
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

P.S. The data that the ajax call returns is json. which is constructed this way

[{
"id": "5f6e8bac-197f-4ae3-8535-6d892a101d17",
"localTitle": "Public"
}]

Upvotes: 0

Views: 60

Answers (2)

khakiout
khakiout

Reputation: 2400

AngularJS controllers aims not to use/create HTML elements directly in their code. You use the view/HTML to render the values returned by the AJAX response.

Controller

... 
$scope.values = [];

...
.success(function (response,status, headers, config){
    // put the response values in a scope object
    $scope.values = response;
})
...

View

<!-- render the values using ng-repeat -->
<div ng-repeat="value in values">
    {{value.localTitle}}
</div>

References

Upvotes: 3

bobijovz
bobijovz

Reputation: 54

https://docs.angularjs.org/api/ng/directive/ngRepeat

just declare your json data in controller with scope then use it on your view

controller.js

$scope.myObj = 'http response here';

view.html

<table>
   <tr ng-repeat="data as myObj"> 
     <td>{{data.localTitle}}</td>
   </tr>
</table>

Upvotes: 1

Related Questions