I have a method in my Web API controller returning a boolean:
[HttpGet]
public bool ValidateEmployee(string id)
{
return myRepository.VerifyEmployeeId(id);
}
and here is my UI that is calling that Web API via Angular;
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Employee ID/PIN</title>
<script src="../../Scripts/angular.js"></script>
<script src="EmployeeLoginCtrl.js"></script>
</head>
<body ng-app="myClassesApp">
<div ng-controller="myClassesController">
<form ng-submit="ValidateEmployeeId()" method="get" id="frmLogin" action="">
<input ng-model="empId" type="text" id="txtEmpId" />
<br />
<input type="submit" value="Submit" id="btnSubmit" />
<br />
<span id="lblMsg">{{EmployeeValidate}}</span>
</form>
</div>
</body>
</html>
and here is my angular controller:
(function () {
angular.module("myClassesApp", []).controller("myClassesController", EmpCtrlFunction);
EmpCtrlFunction.$inject("$scope", "$http");
function EmpCtrlFunction($scope, $http) {
$scope.ValidateEmployeeId = function () {
alert($scope.empId);
$http.get('http://localhost:49358/api/myClasses/ValidateEmployee/' + $scope.empId).
then(function (result) {
alert(result);
$scope.EmployeeValidate = result.data;
});
}
};
})();
When I enter an id and click a button, the line alert($scope.empId); gets executed and then it never gets to $http.get
What am I doing wrong?
dont use alert since alert is blocking and causes all kinds of problems in angular, use console.log instead to dump variable values and use the console tab in your browser to view output
console.log($scope.empId);
use the NET tab in your browser to view what HTTP requests are being made
The way you inject dependencies is wrong. it should be
EmpCtrlFunction.$inject = ["$scope", "$http"];
as $inject is not a function.
Related
I wish to share a service value between one or more controllers (only one in the following example but that's not the point).
The problema is that the value hold in the service is not bound and shown in the view.
The code (derived from angularjs basic service example) is:
(function(angular) {
'use strict';
angular.
module('myServiceModule', []).
controller('MyController', ['$scope', 'notify','$log', function($scope, notify, $log) {
$scope.callNotify = function(msg) {
notify.push(msg);
};
$scope.clickCount = notify.clickCount();
$log.debug("Click count is now", $scope.clickCount);
}]).
factory('notify', ['$window','$log', function(win,$log) {
var msgs = [];
var clickCounter = 0;
return {
clickCount: function() {
clickCounter = msgs.length;
$log.debug("You are clicking, click count is now", clickCounter);
return clickCounter;
},
push: function(msg) {
msgs.push(msg);
clickCounter = msgs.length;
$log.debug("Counter is", clickCounter);
if (msgs.length === 3) {
win.alert(msgs.join('\n'));
msgs = [];
}
}
}
}]);
I wish the counter to be displayed on page:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-services-usage-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myServiceModule">
<div id="simple" ng-controller="MyController as self">
<p>Let's try this simple notify service, injected into the controller...</p>
<input ng-init="message='test'" ng-model="message" >
<button ng-click="callNotify(message);">NOTIFY</button>
<p>(you have to click {{3-self.clickCount}} times more to see an alert)</p>
</div>
<div>You have clicked {{clickCount}} times</div>
</body>
</html>
See it in action on plunker
UPDATE: corrected the trivial errors is html and service code as suggested by #SehaxX
First your HTML is wrong. Your last div is not in the div of Controller, and you dont need the self.
<body ng-app="myServiceModule">
<div id="simple" ng-controller="MyController">
<p>Let's try this simple notify service, injected into the controller...</p>
<input ng-init="message='test'" ng-model="message" >
<button ng-click="callNotify(message);">NOTIFY</button>
<p>(you have to click {{3-self.clickCount}} times more to see an alert)</p>
<div>You have clicked {{clickCount}} times</div>
</div>
</body>
Also in your service you are missing return:
clickCount: function() {
clickCounter = msgs.length;
$log.debug("You are clicking, click count is now", clickCounter);
return clickCounter;
},
And in your controller you only once call the notify.clickCount() so you need to add it to the method:
$scope.callNotify = function(msg) {
notify.push(msg);
$scope.clickCount = notify.clickCount();
$log.debug("Click count is now", $scope.clickCount);
};
Here also a working code pen with "Controller as self" if you want. But then in controller you must use this and not $scope.
Cheers,
I'm new to AngularJS and I'm trying to bind some data I fetch with an Http call when user clicks a button. Data binding works fine when I use it outside of test() but it does not inside test() which gets called on a button click.
What am I doing wrong?
<head>
<script>
function test() {
fetch(url)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var response = myJson;
var results = parseJSON(response);
angular.module("blabla", [])
.controller("myController", function($scope) {
$scope.test= {};
$scope.test.title = "testttt!";
});
});
}
</script>
</head>
<body ng-app="blabla">
<div class="search">
<form id="search_form" method="get" onSubmit="return test()">
<input type="text" class="_search" placeholder="Search" id="search_">
<input title="Search" value="" type="submit" class="search_btn">
</form>
</div>
<div ng-controller="myController">
<h2>Welcome {{test.title}}</h2>
</div>
</body>
Replace onSubmit="return test()" by onSubmit="test()"
The Angular interpreter is trying to invoke the statement (I believe that it thinks it is a function) return (with parameters test()
Also, test() needs to be declared in the $scope of your controller myController.
It might be a good idea to get a skeleton demo Angular app and try to understand how it works by making small modifications.
I am trying to access the class of button which is placed next to paragraph. As soon as the focus gets on paragraph the class of button should change. Please see HTML the code below :
<div>
<span id="key" class="col-lg-2">email : </span>
<span ng-focus="focused($event)" id="value" contenteditable="true">abcd#abc.com</span>
<input type="submit" name="update" value="update"
class="update-hide" data-ng-click="updateValue($event)">
</div>
The angular code for controller is :
var TestParseController = function($scope, $window, $http, $routeParams, $sce,
$compile) {
$scope.focused = function(focusedValue) {
var par = focusedValue.target.parentNode;
var nodes = par.childNodes;
nodes[2].className="update-regular";
}
}
How could this be done in angular way? I know its something like $$nextSibling , but accessing the class name is problamatic. I have googled a lot and found nothing. Please help!!!
Please suggest any dynamic way i can not hardcode any id for button also.
This can be like below:
angular.module("app",[])
.controller("MainCtrl", function($scope) {
$scope.focused = function(focusedValue) {
var par = focusedValue.target.parentNode;
angular.element(par.querySelector("input[type=submit]")).addClass("update-regular");
}
});
.update-regular {
background: red;
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="MainCtrl">
<div>
<span id="key" class="col-lg-2">email : </span>
<span ng-focus="focused($event)" id="value" contenteditable="true">abcd#abc.com</span>
<input type="submit" name="update" value="update"
class="update-hide" data-ng-click="updateValue($event)">
</div>
</body>
</html>
But mostly DOM manipulation must be done via directives. Controller must act mostly like ViewModel. So if you could create a directive and add it to the contenteditable span tag.
angular.module("app", [])
.directive("focusAdjacentButton", function () {
return {
restrict: "AEC",
link: function (scope, element, attrs) {
element.on("focus", function () {
angular.element(element[0].parentNode.querySelector("input[type=submit]")).addClass("update-regular");
});
// if you want to remove the class on blur
element.on("blur", function () {
angular.element(element[0].parentNode.querySelector("input[type=submit]")).removeClass("update-regular");
});
}
}
});
In your HTML:
<span focus-adjacent-button id="value" contenteditable="true">abcd#abc.com</span>
I was just playing around doing some testing, here is some Javascript, that uses Angular JS to post some form data:
<!DOCTYPE html>
<html>
<head>
<title>Add a course</title>
<script type="text/javascript" src="../angular.js"></script>
</head>
<body ng-app="form">
<div ng-controller="formController">
<form class="course-form">
Name: <input type="text" ng-model="course.name" /><br />
Duration: <input type="text" ng-model="course.duration" /><br />
Fee: <input type="text" ng-model="course.fee" /><br />
<input type="button" ng-click="add(course)" value="Add course" />
</form>
</div>
<script>
angular.module('form', [])
.controller('formController', ['$scope', '$http', '$log', function($scope, $http, $log) {
$scope.add = function(courseData) {
var url = "http://localhost:8080/CourseService/courseService/newcourse";
var request = $http({method: 'POST', url: url, data:{name: courseData.name, duration: courseData.duration, fee: courseData.fee}});
request.success(
function(html) {
alert("it succeeded");
}
);
request.error(
function(html) {
alert("it didn't work");
}
);
};
}]);
</script>
</body>
</html>
here is the method that the data is posted to:
#POST
#Path("/newcourse")
#Consumes(MediaType.APPLICATION_JSON)
public Response newCourse(#QueryParam("name") String name, #QueryParam("duration") String duration, #QueryParam("fee") int fee) {
System.out.println(name+""+duration+""+fee);
return Response.status(200).build();
}
The problem is that When I print the values, they are all null except for the fee which is 0, is there a reason why this is? I have checked the values being posted and they are fine and populated.
I did have other ways or writing the above service method, such as using #FormData, I could also have changed the path to be: `("/newcourse/{name}/{duration}/{fee}"), and URI encoding the values in, but this is just the way I ended up testing it.
If you want the data to be received as query params, (i.e. the requested URL will be like http://localhost:8080/CourseService/courseService/newcourse?name=123&duration=456&fee=789) you have to send them using the params option, instead of the data, which specifies the request body:
var request = $http({method: 'POST', url: url,
params:{name: courseData.name, duration: courseData.duration, fee: courseData.fee}});
I've been following a course to learn angularjs and I can't seem to get a simple ng-click binding to work.
HTML:
<body ng-controller="MainController">
<div ng-app="githubViewer">
<h1>{{message}}</h1>
<div>{{ error }}</div>
{{username}}
<form name="searchUser">
<input type="search" placeholder="Username to find" ng-model="username" />
<input type="submit" value="Search" ng-click="search(username)" />
</form>
<div>
<div>{{user.name}}</div>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}">
{{user.gravatar_id}}
</div>
</div>
</body>
Javascript:
(function () {
var module = angular.module("githubViewer", []);
var MainController = function ($scope, $http) {
var onUserComplete = function (response) {
$scope.user = response.data;
};
var onError = function (reason) {
$scope.error = "Could not fetch the user";
$scope.reason = reason;
};
$scope.username = "angular";
$scope.message = "Github Viewer";
$scope.search = function (username) {
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
};
};
module.controller("MainController", MainController);
}());
When you click the search button (search for username "odetocode" or "robconery") it is supposed to display an image but the click event does not seem to be firing. I have searched the documentation and looked over the course again but I can't see what I'm doing wrong.
I'm currently using version 1.2.16 of angularjs.
You have the ng-controller declaration outside of the ng-app declaration right now:
<body ng-controller="MainController">
<div ng-app="githubViewer">
It should be the other way around, or have both on the same element
<body ng-app="githubViewer" ng-controller="MainController">
<div>
AngularJS evaluates your code, and checks for any directives you have declared from the ng-app element down, including the element it is declared on; This currently is missing the ng-controller directive, as it is placed on a parent element of the ng-app element.
You need to put the controller within the context of the module to have it within its scope.
Like so
<body ng-app="githubViewer" ng-controller="MainController">
Demo here