Camila Camila - 5 months ago 9
AngularJS Question

I replaced $scope to a variable and now my angular application doesn't work

I'm doing an Angular application and I read that it's a good practice don't use $scope. So I replaced to a variable, and now the data is not appearing on my page:

It was like this:

observatoryApp.controller('AppController', function AppController($scope, $http){
var $scope = this;
$scope.years = [];
$http.get('json/years.json').then(function(response){
$scope.years = response.data;
$scope.data = $scope.years[0];
});


Now is like this:

observatoryApp.controller('AppController', function AppController($http){
var self = this;
self.years = [];
$http.get('json/years.json').then(function(response){
self.years = response.data;
self.data = self.years[0];
});


And the data are not showing on the index.html page:

<body ng-controller="AppController">
...
<select class="year form-control"
ng-options="year.id for year in years"
ng-model="data">
</select>
...
</body>


What I'm doing wrong?

Answer

I read that it's a good practice don't use $scope

That would have been in context of using controllerAs alias as alternative.

Unless you use that alias you use the injected $scope to assign model properties to. You would never do var $scope = this;