James Satori-Brunet
James Satori-Brunet

Reputation: 901

Angularjs: how to use "this" instead of $scope

I would like to work out how to convert this:

 app.controller('AnswersCtrl', ['$scope', '$http', '$log', '$ionicModal', '$state',     'SuspectService', 
function($scope, $http, $log, $ionicModal, $state, SuspectService) {

    $scope.suspects = [];

    SuspectService.getSuspects().then(function(data){
        $scope.suspects = data;
    });

    $scope.goToClues = function(){      
        $state.go('clues')
    };


   }]);

into something that looks like this:

 app.controller('AnswersCtrl', ['$http', '$log', '$ionicModal', '$state', 'SuspectService', 
function($http, $log, $ionicModal, $state, SuspectService) {

    var self = this;

    self.suspects = [];

    SuspectService.getSuspects().then(function(data){
        self.suspects = data;
    });

    self.goToClues = function(){        
        $state.go('clues')
    };


   }]);

The code which utilises $scope works but the code which utilises this (self) doesn't.

I have tried a couple of variations and haven't been able to get it to work.

Upvotes: 0

Views: 250

Answers (1)

Marc Harry
Marc Harry

Reputation: 2430

It looks like you are almost there in order for this syntax to work in your controllers you also need to change the markup where you define the controller to look like this:

<div ng-controller="AnswersCtrl as vm">
    {{ vm.suspects[0].name}}
</div>

You can see a working example without the extra services you have defined in you example here: http://jsbin.com/zevaluside/3/edit

You will also require Angular 1.2 or higher for this to work as well.

Upvotes: 1

Related Questions