How to access the $ scope variable?

5

I would like to know how I can access the contents of the scope variable in AngularJS?

Theoretically I did everything "correct", ie declaring the variable in controller and assigning values in it:

var app = angular.module('vagalume', []);
app.controller('BandsController', function($scope) {
  $scope.teste = 'VALOR DE TESTE';
  this.lista = [
    {
      nome: 'U2',
      estilo: 'Rock'
    },
    {
      nome: 'Guns And Roses',
      estilo: 'Rock'
    },
    {
      nome: 'Scorpions',
      estilo: 'Rock'
    }
  ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script><bodyng-app="vagalume">
  <div class="artistas" ng-controller="BandsController as bandas">
    {{'TESTE:' + bandas.teste}}
    <ul>
      <li ng-repeat="banda in bandas.lista">{{banda.nome}}</li>
    </ul>
  </div>
</body>

The test never returns anything ...

Link to code: link

    
asked by anonymous 18.08.2015 / 17:29

3 answers

3

Or change $scope.teste to this.teste in js, which will work.

Or in html changes {{'TESTE:' + bandas.teste}} to {{'TESTE:' + teste}}

    
18.08.2015 / 17:55
5

When you access binds the property with the variable

$scope.teste

You can not access it with the controller alias {{bandas.teste}}

You can access it as {{teste}} .

To access the properties created in the Controller Alias, you have to create it in the controller as follows.

this.teste = valor (This = Controller)

app.controller('BandsController', function ($scope) { this == controller }

    
18.08.2015 / 19:03
2

The reference to the scope needed to be fixed. The example below shows your content working:

var app = angular.module('vagalume', []);
	app.controller('BandsController', function ($scope) {		
		$scope.teste = 'VALOR DE TESTE';
		$scope.lista = [
			{
				nome: 'U2',
				estilo: 'Rock'
			},
			{
				nome: 'Guns And Roses',
				estilo: 'Rock'
			},
			{
				nome: 'Scorpions',
				estilo: 'Rock'
			}
		];
	});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><bodyng-app="vagalume">
	<div class="artistas" ng-controller="BandsController as bandas">
		{{'TESTE:' + teste}}
		<ul>
			<li ng-repeat="banda in lista">{{banda.nome}}</li>
		</ul>		
	</div>	
</body>
    
18.08.2015 / 18:11