So basically wwhat I'm trying to do is take input of two numbers n1 and n2 and then print their sum all using angular. I have used bootstrap for styling. But i noticed nothing was happening so to check i added alert()
function in the function to be called but still it's not getting accessed somehow. I dont know jQuery.
PS: when I use text1+text2
it's concatinating the string instead of printing the sum
This is my html:
<!DOCTYPE html>
<html ng-app="store">
<head >
<title>Trying Angular</title>
<link rel="stylesheet" type="text/css" href="bootstrap/dist/css/bootstrap-theme.css">
<link rel="stylesheet" type="text/css" href="bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<form class="form-inline" style="border: 2px solid blue; max-width:500px;" ng-controller="formCtrl as formCtrl" ng-submit="formCtrl.submit()">
<div class="form-group">
<label>Enter n1</label>
<input type="text" class="form-control" placeholder="enter the first number" ng-model="text1">
<p>{{ text1}}</p>
</div>
<div class="form-group">
<label>Enter n2</label>
<input type="text" class="form-control" placeholder="enter the second number" ng-model="text2">
<p >{{text2}}</p>
</div>
<div class="form-group" style="display:block; margin:10px auto; margin-left:370px;">
<input type="submit" class="form-control" >
</div>
<p> Your SUM of two numbers is ={{text1+text2}}</p>
</form>
<script src="angular.min.js"></script>
<script src="exp1.js"></script>
<script src="jquery.min.js"></script>
<script src="bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</html>
This is my angular code:
(function(){
var app=angular.module('store',[]);
var n1=0;
var n2=0;
app.controller('formCtrl',function(){
this.submit=function(){alert("successful");}; // <----- alert()
});
})();
As explained in the documentation for the ngController directive, there are two ways to access the members of a controller:
as <scopeProperty>
syntax, and access it using the <scopeProperty>
name:<form class="form-inline" style="border: 2px solid blue; max-width:500px;" ng-
controller="formCtrl as fc" ng-submit="fc.submit()">
Here, fc
is being declared as the name for the controller instance, and its properties are accessed with fc.
$scope
into the controller and add properties to that:app.controller('formCtrl', ['$scope', function($scope){
$scope.submit = function(){alert("successful");};
}]);
<form class="form-inline" style="border: 2px solid blue; max-width:500px;" ng-
controller="formCtrl" ng-submit="submit()">
Here, the controller's properties are added to the $scope
and this allows us to access them directly in the HTML without using the dot notation.
The page linked to above compares and contrasts the two approaches. You were not exactly using either, and that's why you were having trouble.