C Ivemy C Ivemy - 5 months ago 21
Javascript Question

Can't access controller properties in view with UI router and 'controller as' syntax

I am using ui-router for my routing, and am going to be using nested scopes and therefore want to be using the 'controller as' syntax. However, I can't work out the correct syntax / combinations to access the controller object properties in my view.

app.js (sets up routing)


(function() {

angular

.module('ICP_App', ['ui.router', 'satellizer', 'ngMaterial', 'ngMessages', 'xeditable'])

.config(function($stateProvider, $urlRouterProvider, $authProvider) {

$urlRouterProvider.otherwise('dashboard');

$stateProvider
.state('clients', {
url: '/clients',
templateUrl: '../partials/clients-index.html',
controller: 'ClientsController as ClientsCtrl'
})
// more routes here...

})();


ClientsController.js


(function() {

angular.module('ICP_App')
.controller('ClientsController', function($http) {
$http.get('http://api.icp.sic.com/clients')
.success(function(clients) {
var vm = this;
vm.clients = clients.data;
console.log(vm.clients);
})
.error(function(error) {
// handle here
})
});

})();


index.html


<body ng-app="ICP_App" ng-cloak>

<!-- sidebar, header etc -->

<div ui-view></div> <!-- pull in view -->

</body>


Finally,
clients-index.html
partial

<div class="content">
<div class="pane" ng-repeat="client in clients">
{{ client.name }}
</div>
</div>


I have also tried
client in vm.clients
, to no avail.

Is there a problem with my controller as syntax? As I am using controller as in my ui-router code, yet not again when creating my controller. If I use controller as again in my controller, it errors (
Argument ClientsController is not a
).

I should point out that console logging vm.clients does give me the data in the console, I just can't seem to access it in my view.

Thanks in advance.

Answer

Modify your ClientsController as follow

(function() {

angular.module('ICP_App')
    .controller('ClientsController', function($http) {
        var vm=this;
        $http.get('http://api.icp.sic.com/clients')
            .success(function(clients) {                   
                vm.clients = clients.data;
                console.log(vm.clients);
            })
            .error(function(error) {
                // handle here
            })
    }); })();

Modify client-index.html as following

<div class="content">
<div class="pane" ng-repeat="client in ClientsCtrl.clients">
    {{ client.name }}
</div>

Below link will help you to understand controller as syntax more deeply

https://toddmotto.com/digging-into-angulars-controller-as-syntax/