Reputation: 81
I'm trying to use ng-click to call a function in my controller, but I haven't been able to get that to work. I've stripped everything down to its simplest form, so that I now have this:
<button id="submitBtn" type="submit" class="btn btn-default"
ng-click="count = count + 1; count = count + 2; alert('hello');" >Submit</button>
The first two statements (count = count + 1; count = count + 2;) execute just fine, but it won't call the alert function. When I take out the two count incrementing statements, the alert still won't work. Anytime I try to call a function, it fails, but plain old Javascript works.
(Just an FYI, I have Javascript down the page that prevents the form from submitting and triggering a postback).
Edit:
I'll include my controller's code for this:
myApp.controller('LawSearchController', ['$scope', function ($scope) {
$scope.alert = function (text) {
alert(text);
};
}]);
Upvotes: 1
Views: 689
Reputation: 371
I don't believe it's the intended use of the ngClick to contain a lot of javascript. You should only call 1 function in the NG click and that function should call the others
I belive it should be implemented more like the following as well I think you need to get the alert function from the root scope. or
HTML Snippit
<button id="submitBtn" type="submit" class="btn btn-default" ng-click="submitAndAlert()" >Submit</button>
Controller
myApp.controller('controllerName', ['$scope', '$rootScope', function ($scope, $rootScope) {
$scope.count = 0;
$scope.submitAndAlert = function(){
count += 1;
count += 2;
alert('hello');
}
$scope.alert = function (text) {
// $rootScope.window.alert(text);
$rootScope.alert(text);
};
}]);
Upvotes: 0
Reputation: 81
For future reference, here was my issue:
I had tried placing my ng-controller directive with the <form>
tag on my page. This is an asp.net application with a MasterPage, and (why, I don't know) the form gets replaced when creating the page with a new form that wraps all of the content. The result is that my ng-controller directive is gone.
I had also tried placing the ng-controller directive within the <asp:Content>
tag, but that also gets removed.
The solution:
Wrap my page's <form>
in a <div>
and put the ng-controller directive there.
Upvotes: 0
Reputation: 2383
As one of the answeres pointed out, you need to have a function in your controller as such:
$scope.alert = function(arg) {
// Do something
};
Upvotes: 0
Reputation: 23662
All functions you call in an ng-expression
are in the context of $scope.
So when you say alert()
it compiles to scope.alert()
which is undefined, and fails silently.
In your controller, include the code
$scope.alert = alert
Upvotes: 5