0

This is my current ng-click:

ng-click="avatarMenu = !avatarMenu"

<div class="avatar"
     ng-click="avatarMenu = !avatarMenu"
     ng-class="{ active: avatarMenu }">
     <img src="_sources/images/joe.png" title="settings" alt="user avatar" />
</div>

Now I want to create a $scope function that does something else when you click on that element, tried the following, but got errors:

ng-click="avatarMenu = !avatarMenu, getMenuClick('clicked')"

Also tried to move the animation/boolean logic into the function inside my app.js but got avatarMenu is not defined, guess since it's not on the HTML anymore:

$scope.avatarMenu = false;

$scope.avMenu = {};
$scope.avMenu.getMenuClick = function(the_id) {
    avatarMenu = !avatarMenu
    selectAddress(the_id);
};

How would you have both the animate/boolean login on there as well as the function?

4
  • You need to use $scope.avatarMenu inside the controller Commented Jan 7, 2015 at 20:22
  • I have it in the controller :( Commented Jan 7, 2015 at 20:24
  • 1
    I meant that you should do: $scope.avatarMenu = !$scope.avatarMenu. Of course, avatarMenu is not defined - the controller is just a regular JS function and you don't have var avatarMenu = false; there. Commented Jan 7, 2015 at 20:27
  • Ah thanks! Want to post that as an Answer? Slowly getting $scope Commented Jan 7, 2015 at 20:28

2 Answers 2

1

ViewModel variables defined in the Controller function need to be declared on the $scope parameter (as you did) or, if you are using Controller As approach - as the property of the Controller.

So, with the $scope-approach:

$scope.avatarMenu = ...;
...
  $scope.avatarMenu = !$scope.avatarMenu;

and in the View:

<div ng-class="{ active: avatarMenu }">

or, with ControllerAs-approach:

this.avatarMenu = ...;
...
   this.avatarMenu = !this.avatarMenu;

And in the View:

<div ng-controller="MyCtrl as vm">
   ...
   <div ng-class="{ active: vm.avatarMenu }"></div>
</div>

Remember, that at the end of the day, a Controller is just a regular JavaScript function without any "magic" behind it.

Also, as suggested in another answer, you could also use a semi-colon ; to separate commands in the View, but I would minimize the amount of logic in the View.

Sign up to request clarification or add additional context in comments.

Comments

1

Use a semi-colon, instead of a comma.

avatarMenu = !avatarMenu; getMenuClick('clicked')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.