Pass $scope data from controller to view

728 views Asked by At

I want to display $scope.predicate and $scope.reverse values into my view(in the <p> tag ). It seems that using {{ }} expression is not working.

app.js:

 var app = angular.module('testApp', []);
 app.controller('TestController', function($scope,$http ){
 var vm = this;
 vm.rezdata = [];
 $http.get("some rest resource...")
      .then(function(response) {
          vm.rezdata =  response.data;
          $scope.predicate = 'username';
          $scope.reverse = true;
      });
});

HTML:

<body ng-app="testApp">
    <h1>Users table </h1>  
    <table class="table table-striped" ng-controller="TestController as test">
        <p> Sorting predicate {{predicate}}; reverse = {{reverse}} </p>
        <thead>
            <tr>
                <th>#</th>
                <th>
                    Username
                </th>
                ... 
            </tr>
        </thead>
        <tbody>     
            <tr ng-repeat="datafinal in test.rezdata" >  
                <td>{{ datafinal.id}} </td>
                <td>{{datafinal.username}} </td>
                ...
            </tr>
        </tbody>        
    </table>
</body>
1

There are 1 answers

5
Pankaj Parkar On BEST ANSWER

Put ng-controller="TestController as test" on body tag.

Also as you are using controller as syntax while using controller, so the value inside the controller context (this) is accessible on HTML by its alias test. {{test.predicate}}; reverse = {{test.reverse}} should work.

But technically you shouldn't use both $scope & this in same controller while using controller as, which will again create a confusion. So I'd suggest you to change $scope to vm.

<p>Sorting predicate {{predicate}}; reverse = {{reverse}}</p>
<table class="table table-striped" ng-controller="TestController as test">
   ...  
</table>