lrningPrgrming
lrningPrgrming

Reputation: 31

ng-click change value of a var

I'm trying to set ng-click to modify a var inside my controller.

I've tried to set ng-click to target the var mar.

<div class="Button" ng-click="mar = 'test-2';">

inside the controller.js i have this

eventsApp.controller('EventController', function EventController($scope) {

    //variables
    var mar = 'test-1';

}

So what i was hoping is to get var mar changed to 'test-2'; but, my html page just keeps displaying test-1. is there a directive or a way to dynamically change var mar?

I do not want to have to setup a $scope.mar = 'test-1' and manipulate that. How can i do this? Thank you.

Upvotes: 0

Views: 1620

Answers (1)

MSclavi
MSclavi

Reputation: 427

You should declare it on $scope and you have a typo

eventsApp.controller('EventController', function EventController($scope) {

    //variables
    $scope.mark = 'test-1';

}

EDIT

If you don't want to use $scope you have to assign this to a variable inside your controller. Here is a little example.

var app = angular.module('app', []);

app.controller('EventController', function ($scope) {

    //variables
    var vm = this;
    vm.mar = 'test-1';

});
<div ng-app="app" ng-controller="EventController as ctrl">
  <button class="Button" ng-click="ctrl.mar = 'test-2';">
    Click me!
  </button>
  <p>{{ctrl.mar}}</p>
</div>

If you want to use the variable inside a function on the controller you just use $scope.mar or vm.mar.

Upvotes: 3

Related Questions