Why Is Ng-click Not Working?
Solution 1:
Angular's expressions do not use the eval
function so unless you have defined a function named alert
in your scope chain somewhere it will not execute.
https://docs.angularjs.org/guide/expression#context
Angular does not use JavaScript's eval() to evaluate expressions. Instead Angular's $parse service processes these expressions.
Angular expressions do not have access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.
Instead use services like $window and $location in functions called from expressions. Such services provide mockable access to globals.
So you would have to define such a function on your scope:
app.controller('MainCtrl', function($scope,$window) {
var that = this;
$scope.showTest = true;
$scope.alert = function() {
$window.alert('angular click');
};
});
DEMO
angular.module('plunker', []);
var app = angular.module('plunker', [
'plunker'
]);
app.config( function( ) {
'use strict';
});
app.controller('MainCtrl', function($scope,$window) {
var that = this;
$scope.showTest = true;
$scope.alert = function(text){
$window.alert(text);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
<div ng-show="showTest" ng-click="alert('angular click')" onclick="alert('default click')">Default or angular click?</div>
<div ng-show="dontShowMeIsNotDefinedSoIWontShow" >Not showing me, I know angular is working!</div>
</div>
Solution 2:
Added an alert
attribute to your controller definition:
app.controller('MainCtrl', function($scope) {
var that = this;
$scope.showTest = true;
$scope.alert = function(msg) {
alert(msg);
};
});
I think the issue is that the ng-click
directive will automatically interpret whatever you put inside in the scope of the controller object. So if the controller doesn't have an alert
attribute, nothing happens.
Post a Comment for "Why Is Ng-click Not Working?"