Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-click event is not firing on span element

Tags:

angularjs

Why is the ng-click not working in the code below? It should be simple. What am I missing. Thanks

(function() {
    'use strict';
    // Set up the app.
    var mainApp = angular.module('mainApp', []);

    // Create a controller.
    mainApp.controller('navController', ['$scope', '$log' ,function($scope, $log) {
        //$scope.firstName= "John";
        //$scope.lastName= "Doe";,
        $scope.openTab = function (tabNumber) {
            $log.log(tabNumber);
        };

        var s =1;
    }]);
}());
<!DOCTYPE html>
<html>
    <head>
        <script src="/js/angular.js"></script>
        <script src="/js/app/app.js"></script>

        <link rel="stylesheet" href="/css/styles.css" />

    </head>
    <body ng-app="mainApp">
        <div class="navigation" ng-controller="navController as nc">
            <!--<p>Name: <input type="text" ng-model="name"></p>
            <p ng-bind="name"></p>
            <p>{{name}}</p>
            -->
            <span ng-click="nc.openTab(1)" class="btn"> tab 1</span>
            <span ng-click="nc.openTab(2)" class="btn"> tab 2</span>
            <span ng-click="nc.openTab(3)" class="btn"> tab 3</span>
        </div>
    </body>
</html>
like image 310
Hello-World Avatar asked Feb 20 '16 06:02

Hello-World


2 Answers

When you use controllerAs, you have to bind variables and methods directly to the controller instance, this, instead of $scope.

// this.firstName = "John";
// this.lastName = "Doe";
this.openTab = function (tabNumber) {
    $log.log(tabNumber);
};

Because the controllerAs sets the controller instance, this in the controller function, to $scope.nc.

like image 73
Shuhei Kagawa Avatar answered Oct 18 '22 22:10

Shuhei Kagawa


You are using $scope in the controller but in the view you are using as .

If you want to use as badly then your method in controller should be using this keyword

Like this

this.openTab = function (tabNumber) {
    $log.log(tabNumber);
};

But if want to use controller scope then your view should be

<span ng-click="openTab(1)" class="btn"> tab 1</span>
<span ng-click="openTab(2)" class="btn"> tab 2</span>
<span ng-click="openTab(3)" class="btn"> tab 3</span>
like image 38
Anik Islam Abhi Avatar answered Oct 18 '22 22:10

Anik Islam Abhi