angularjscontrollerng-admin

Angular js - Call function inside controller from view in ng-admin


I am working with the feature of multiple languages for ng-admin. In the file header.html, I have added a dropdown with a list of languages. Clicking each option fires a function call.

The function itself is inside a controller in /js/main.js

Clicking in any of the languages results in ReferenceError: serve_language is not defined.

This is the content of both files:

header.html

<ul class="nav navbar-top-links navbar-right hidden-xs">
    <li uib-dropdown ng-controller="languageCtrl">
        <a uib-dropdown-toggle href="#" aria-expanded="true">
            <i class="fa fa-user fa-lg"></i>&nbsp; Language&nbsp;<i class="fa fa-caret-down"></i>
        </a>
        <ul class="dropdown-menu dropdown-user" role="menu">
            <li><a href="#" onclick="serve_language('en')"><i class="fa fa-sign-out fa-fw"></i> English</a></li>
            <li><a href="#" onclick="serve_language('ge')"><i class="fa fa-sign-out fa-fw"></i> German</a></li>
            <li><a href="#" onclick="serve_language('fr')"><i class="fa fa-sign-out fa-fw"></i> French</a></li>
            <li><a href="#" onclick="serve_language('sp')"><i class="fa fa-sign-out fa-fw"></i> Spanish</a></li>
        </ul>
    </li>
</ul>

main.js

'use strict'
var myApp = angular.module('myApp', ['ng-admin','ng-admin.jwt-auth', 'nvd3']);
myApp.controller('languageCtrl', ['$translate', '$scope', function ($translate, $scope) {
    $scope.serve_language = function (langKey) {
       console.log("@langctrl"); 
    };
}]);

I also tried calling the function as languageCtrl.serve_language(), but that resulted in ReferenceError: languageCtrl is not defined


Solution

  • You should change onclick to ng-click

    <ul class="dropdown-menu dropdown-user" role="menu">
                <li><a ng-click="serve_language('en')"><i class="fa fa-sign-out fa-fw"></i> English</a></li>
                <li><a ng-click="serve_language('ge')"><i class="fa fa-sign-out fa-fw"></i> German</a></li>
                <li><a ng-click="serve_language('fr')"><i class="fa fa-sign-out fa-fw"></i> French</a></li>
                <li><a ng-click="serve_language('sp')"><i class="fa fa-sign-out fa-fw"></i> Spanish</a></li>
            </ul>