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>
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
.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With