I'm using angular since 1 little week now and i have encounter a strange behavior (and i don't know why i didn't see that earlier because it's look like a pretty basic error).
I have a controller let's say HomeController which define two scope function : foo() and bar() and an object "var myVar = 5", I would like to change the value of myVar in foo() and write it's content in bar().
The problem is, it's look like that foo() does not modify myVar. I'm not still very aware about scopes in angular, and how they interact, but i think that my $scope in foo() is a different scope, a copy of the actual controller scope. so modifying it will not modify the controller one.
But how can i achieve this ?
Edit : Add all used code
Edit 2 : Add plunker : http://plnkr.co/edit/DGzw0UxjBeND3hQWK3o3
Here is my Index.html
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<!-- CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css">
<!-- JS -->
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-route.js"></script>
<!-- Loading angular App -->
<script src="app.js"></script>
<!-- Loading angular controllers -->
<script src="homeController.js"></script>
</head>
<body ng-app="TemplateApp">
<div ng-view></div>
</body>
</html>
app.js :
var app = angular.module('TemplateApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'homeController'
})
});
home.html :
<div class="row">
<div class="col s6">
<a class="btn" href="#" ng-click="foo()">call foo</a>
</div>
<div class="col s6">
<a class="btn" href="#" ng-click="bar()">call bar</a>
</div>
</div>
And finally homeController.js :
angular.module('TemplateApp').controller('homeController', [ '$scope', function($scope) {
$scope.myVar = 5;
$scope.foo = function() {
$scope.myVar = 10;
console.log($scope.myVar); // display 10
};
$scope.bar = function() {
console.log($scope.myVar); // display 5 Should be 10
};
}])
Thanks