Problem with ng-click + Angularjs menu

Asked

Viewed 535 times

5

I have a menu that is filled in dynamically:

<div ng-controller="menuDinamicoController as vm">
  <div ng-show="isAutenticado">
    <img src="{{vm.fotoUser}}" id="imagemUsuario" width="50px" />
    <label id="nomeUsuario" ng-model="nomeUser">{{vm.nomeUser}}</label>
    <div id="menu">
        <ul>
            <li ng-repeat="x in menu">
                <a href="{{x.Link}}" ng-click="vm.{{x.Id}}()">{{x.Nome}}</a>
            </li>
        </ul>
    </div>
  </div>
</div>

The link structure is being returned correctly:

<a href="#" ng-click="vm.sair()" class="ng-binding">Sair</a>

In my controller I have the following function:

vm.sair = function () {
        $cookieStore.remove("Usuario");
        $cookieStore.remove("Token");
        $location.path("/");
};

However, ng-click is not calling the function. And the following error occurs: Syntax Error: Token 'x.Id' is at column {2} of the Expression [{3}] Starting at [{4}].

  • I don’t know if this is possible because ng-click does not wait for the keys (ng-click="vm.{{x.Id}}()") that it used to fill the Id, then it gets confused when executing the function call. I’ll run some tests here, if I get something I’ll let you know.

1 answer

1


One way that can work is this:

<li ng-repeat="x in menu">
    <a href="{{x.Link}}" ng-click="vm.runFunction(x.Id)">{{x.Nome}}</a>
</li>

In your controller (example in coffee script, you can convert to javascript if you want):

runFunction: (id)->
    if 'sair' == id
      @sair()

I do not know if it is very gambiarra to do this but I used in a specific case here and it worked right.

Take a look at this link also. If you use this logic in ng-repeat instead of select I believe it also works.

  • That way it worked. I tested another way, using only ng-click="vmx Id." and I got the same result. Thank you !

  • When the answer solves your problem, click accept the answer please facilitate viewing the solution of the problem for those who need it, thank you very much.

Browser other questions tagged

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