How to access the $Cope variable?

Asked

Viewed 1,134 times

5

I wonder how I can access the contents of the variable scope 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>

<body ng-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 the code: http://jsfiddle.net/v0pLv0ny/

3 answers

5

When you access links the property with the variable

$scope.teste

you cannot access it with the Controller Alias {{bandas.teste}}

you can access it as follows {{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 }

  • Thanks for the description on the difference between this and $Cope !

  • +1 for describing the correct reason. =)

3


Or mute $scope.teste for this.teste no js, that will work.

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

2

The reference to the scope needed to be corrected. 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>
<body ng-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>

  • Thanks guy was that same ! vlw

  • @Douglasdossantos always a pleasure to help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.