简体   繁体   中英

Pass $scope data from controller to view

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>

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}} {{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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM