How to retain the variable's value of JSP using AngularJS - angularjs

I am new to AngularJS. I am trying learn to pass the value of a variable to the angularJS.
But for some unknown reason, I am not being able to do.
Below is the .jsp page which I think is correct:
<body >
<div ng-controller="customersController">
<label>Value</label>
<input type="text" ng-model=something></input>
<button ng-click="punchIt()">click me!</button>
<br>Obtained value : {{ value }}
</div>
</body>
In the respective .js page, value passed from .jsp file is not getting retained.The first alert function should return assumed : something's value,but it is returning assumed : undefined.
Below is the .js file:
var myApp = angular.module("getInfo", []);
myApp.controller("customersController", function($scope, $http){
$scope.punchIt = function ($scope, $http) {
var data = {Value: $scope.something};
alert("assumed : "+ $scope.something);
$http.post("http://localhost:8082/HelloWorldWS/services/HelloWorldImpl",data)
.success(function (data, status, header) {
alert("in success " + data);
$scope.value = data;
}).error(function (data) {
alert("in error method " + status);
$scope.value = "error "+ data;
});
};
});
Please suggest some way out.
Thanks.

You are expecting two variables ($scope and $http) in your punchIt() function declaration but not passing these when you call it on button click. Thus inside your punchit() function, both $scope and $http variables would be initialized to nothing (read undefined).
You actually dont need to pass these parameters to your function. Your controller already has these services injected in it via your controller declaration.
Also declare/initialize the name variable in your controller. Else, if you do not enter anything in the input field and try to access it in your $scope, you will retrive it as undefined.
Your code changes would look as below:
myApp.controller("customersController", function($scope, $http){
$scope.name=null;
//OR $scope.name='';
$scope.punchIt = function () {
...
}
}

Related

Data not passing between Controllers

Hi I am trying to pass data from one Controller to another but the data is not displaying on the other end of UI .
this is my service code :-
app.factory('ServiceF', function($rootScope) {
var service = {};
service.data = false;
service.sendData = function(data){
this.data = data;
$rootScope.$broadcast('data_shared');
};
service.getData = function(){
return this.data;
};
return service;
});
Controller 1 Code :-
app.controller('Ctrlone', ["$scope", "ServiceF", function ($scope, ServiceF) {
$scope.Info= {};
$scope.ser= function(){
ServiceF.sendData($scope.Info);
console.log($scope.Info);
};
}]);
The $scope.Info data is coming successfully here from other source which I haven't posted . But it is coming.
Controller 2 :-
app.controller('Ctrltwo', ["$scope" ,"ServiceF",
function($scope , ServiceF) {
$scope.Info= '';
$scope.$on('data_shared',function(){
var good = ServiceF.getData();
$scope.Info = good;
});
}]);
UI where I want to display info :-
<div class="col-sm-8">
<h1 class="mainTitle">Ok Start </h1>
<h2>{{good}}</h2>
</div>
Button click function from 1st UI :-
<label class="cardlabel" style="width:11vw" ui-sref="uitwo" ng-click="ser()">Send</label>
Now where am I going wrong ? Info is not displaying on 2nd UI. And how can I check if data is passing on Service ?
You have no attribute named good in your scope. So {{ good }} will always be empty.
The scope attribute is named Info. So you want {{ Info }}.

Ui bootstrap doesn't show after adding object to controller

So my ui bootstrap model window is working correctly but when I add an object to the controller it stops showing and it doesn't give me any error in consol.
When my controller looks like this:
"use strict";
app.controller('RegisterModalCtrl', ['$scope', '$location', '$uibModalInstance', '$http', 'ngAuthSettings', 'registerService',
function($scope, $location, $uibModalInstance, $http, ngAuthSettings, registerService) {
var $ctrl = this;
$ctrl.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
/*
$ctrl.registerInfo = {
email: $ctrl.registerData.email,
nick: $ctrl.registerData.nick,
password: $ctrl.registerData.password,
password_confirmation: $ctrl.registerData.confirm_password
};
*/
$ctrl.registerSubmit = function(registerInfo) {
console.log('im in registerSubmit controller function');
registerService.registerUser(registerInfo);
$uibModalInstance.dismiss('cancel');
};
$ctrl.showCookiesRules = function() {
$location.url("/cookiesrules");
$uibModalInstance.dismiss('cancel');
};
$ctrl.showRules = function() {
$location.url("/rules");
$uibModalInstance.dismiss('cancel');
};
}]);
Everything works just fine but when i delete /* just before registerInfo object it stops showing. What is wrong with this object? I want it to create this object to pass it in function and then pass it to function in service.
So what you should do is initiate $ctrl.registerInfo:
$ctrl.registerInfo = {};
The data doesn't exist when the controller runs, so you are trying to set the properties of $ctrl.registerInfo without non-existent data. Once your form is filled out, the properties/data will be set.
An alternative option would not be to initialize at all, and simply set your form model to registerData.confirm_password, and when you call registerSubmit, call it with registerSubmit(registerData). That will send the data to that method without having to initialize in the controller:
<input type="text" placeholder="powtórz hasło"
ng-model="registerData.confirm_password" />
<!-- abbreviated (other form fields here -->
<input type="submit" ng-click="registerSubmit(registerData)" />
If you need the data afterwards, in registerSubmit, add a line:
$ctrl.registerInfo = registerInfo;
However, I am not sure you'd want to hang onto the password there.
AngularJS Form Docs: https://docs.angularjs.org/guide/forms

AngularJs, Passing optional parameters to the URL based on user input

I am trying to consume my ASP.NET Web API using AngularJs. The problem is that i want to pass optional parameters to the url based on the user input(2 Html Text Boxes) but i don't know how.
This is my ASP.NET Web API Controller
[Route("api/JobShow/{keyword}/{location}")]
public class JobShowController : ApiController
{
[HttpGet]
public PageResult<sp_JobSearch_Result> Get(ODataQueryOptions<sp_JobSearch_Result> options, string keyword = null, string location = null)
{
ODataQuerySettings settings = new ODataQuerySettings()
{
PageSize = 20
};
JobWindow obj = new JobWindow();
IQueryable results = options.ApplyTo(obj.showJobs(keyword, location).AsQueryable(), settings);
return new PageResult<sp_JobSearch_Result>(
results as IEnumerable<sp_JobSearch_Result>,
Request.GetNextPageLink(),
Request.GetInlineCount());
}
}
And this is my AngularJS controller
angular.module('JobSearch.SiteController', []).controller('JobSearchCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('/api/JobShow').success(function (data) {
$scope.model = data;
});
}]);
Example of the url then would be .../api/JobShow/Java/Toronto. Thank you all.
You can try ngResource !
You first need to include ng-resource
<script src="angular.js">
<script src="angular-resource.js">
You can get it via Bower or CDN, or whichever way you got AngularJS.
HTML:
<body ng-app="MyApp">
<div ng-controller="MyCtrl">
<label>Keyword: <input type="text" ng-model="keyword" /></label>
<label>Location: <input type="text" ng-model="location" /></label>
<button ng-click="getJobShowPage(keyword, location)">Search</button>
</div>
</body>
Controller:
angular
.module('MyApp', ['ngResource']) // Include the ngResource module here
.controller('MyCtrl', ['$scope', '$resource', function($scope, $resource){
// Create the $resource
var JobShowPage = $resource('/api/JobShow/:keyword/:location', {keyword: "#keyword", location: "#location"})
// Make a scope function to use the resource properly
$scope.getJobShowPage = function(keyword, location) {
var parameters = {};
if (keyword) {
parameters["keyword"] = keyword;
if (location) {
parameters["location"] = location;
}
}
return JobShowPage.get(parameters);
};
}]);
Input/Outputs:
When the user enters nothing and clicks 'Search', the HTTP request would be /api/JobShow
If only the keyword is entered, the HTTP request would be /api/JobShow/{{keyword}}
If both the keyword and location is entered, the HTTP request would be /api/JobShow/{{keyword}}/{{location}}
If only the location is entered (no keyword), the HTTP request would be the vanilla one /api/JobShow
You can consume the return value of the $resource query like a promise:
JobShowPage.get(parameters).$promise.then(function(response){
// Do Stuff
$scope.model = response.data;
});
by callbacks:
JobShowPage.get(parameters, function(err, response){
// Do Stuff
$scope.model = response.data;
});
Or auto unwrap it:
// This works, but it's asynchronous
// Useful if consuming directly from the Angular Template
$scope.model = JobShowPage.get(parameters);
Based on your code, I'm going to assume you have 2 textboxes and a search button, and when the search button is pressed, you want to call your GET endpoint. For this scenario, what you'll want to do is bind the textbox inputs to your scope and bind the search button using ng-click to a function in your scope that will call your endpoint. It might look something like this:
controller
angular.module('JobSearch.SiteController', [])
.controller('JobSearchCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.getResults= getResults;
function getResults() {
$http.get('/api/JobShow/' + $scope.keyword + '/' + $scope.location).success(function (data) {
$scope.model = data;
});
}
}]);
html
<div ng-controller="JobSearchCtrl">
<input type="text" ng-model="keyword">
<input type="text" ng-model="location">
<button type="button" ng-click="getResults()">Search</button>
</div>

AngularJS: code not working when iterating through object [duplicate]

This question already has answers here:
'this' vs $scope in AngularJS controllers
(7 answers)
Closed 6 years ago.
I am trying to populate a list of employee objects from my controller empctrl in a template.
Here's the controller:
app.controller('employeeController', function ($scope, employeeService) {
this.employees = {};
this.populateTable = function (data) {
this.employees = data;
};
var error = function (err) {
console.log("Error: " + err);
};
// Call Service to List all Employees
console.log("Service called to populate table.");
employeeService.output().then(this.populateTable, error);
this.populateTable();
});
However, this code that I wrote isn't working:
<div ng-repeat="employee in empctrl.employees.allEmployees" class="table_row">
<div class="table_column" style="width:2%">{{ $index + 1 }}</div>
<div class="table_column" style="width:8%">{{ employee.employeeName}}</div>
<!-- 7 more columns -->
</div>
Nothing shows up in the UI.
Instead, if I write $scope.employees in the controller, it works:
<div ng-repeat="employee in employees.allEmployees" class="table_row">
Since I know how tempting it is to do $scope.<everything> in the controller, I'm trying to avoid using $scope as much as possible.
If someone could demonstrate the proper use of $scope and difference betwee alias.abc and $scope.abc (where alias is an alias of controller), I'll be thankful.
Edit: Exact same question is this: 'this' vs $scope in AngularJS controllers
Thanks for this link, PankajParkar.
The problem is this which you are accessing inside populateTable function is not this which you have there in your controller function.
Better do keep this variable inside some variable, so that by having it you will make sure you are referring to correct object.
Controller
app.controller('employeeController', function ($scope, employeeService) {
var vm = this;
vm.employees = {};
vm.populateTable = function (data) {
vm.employees = data;
};
var error = function (err) {
console.log("Error: " + err);
};
// Call Service to List all Employees
console.log("Service called to populate table.");
employeeService.output().then(vm.populateTable, error);
vm.populateTable();
});
For more detail, I'd highly recommend you to readup on this article
If you are confused with this vs scope then do read up on this answer
Add your variables to the $scope instead of this like:
$scope.customers = {};
$scope.populateTable = function (data) {
$scope.employees = data;
};
Edit: both methods work. See this article for a in depth explanation.
Substituting "this" to vm (View-Model) will solve your issue. Not polluting $scope object is a groovy thing. this is a global context and its value depends on a function call.
So, in your controller just assign,
var vm = this;
vm.empTable = function (data) {
vm.employeeList = data.data;
};
..and use the vm object elsewhere in your controller. It will be useful to keep the code clean while working with multiple controllers in a view.
Don't forget to give an alias name to the controller,
<div ng-controller="MainCtrl as main">
<div ng-repeat=" employee in main.vm.employeeList ">
{{employee.name}}
</div>
</div>

Execute scope function from service parameter

I am trying to create a service when I can set my formSubmit.
For example. In controller A I call "service.setFormSubmit(doThis(obj))" and in controller B I call "service.getFormSubmit()". Where it will execute the function doThis(obj) in controller B.
UPDATE - Re-formulated question.
I have 1 view where I want to edit or create a category. This means I need a dynamic ng-submit. I want to to this in the controller. So like this:
$scope.editCategory = function(obj) {
$scope.formSubmit = 'editCategory'
}
And on the create I want to change the formSubmit var to createCategory of course.
So I can make a difference between creating and editing the category.
Is this possible? Would be really nice if someone has a way to do this..!
Thanks in advance!
Instead of passing around strings which need to be eval'ed, use the service to share functionality directly between controllers.
The service can be dirt-simple:
.factory('MyService', function(){
var service = {};
return service;
});
Once injected and assigned to scope variables in both controllers you have an intermediary unit which can act as a modifiable channel for cross-controller collaboration.
.controller('FirstController', function($scope, MyService){
$scope.service = MyService;
})
.controller('SecondController', function($scope, MyService){
$scope.service = MyService;
$scope.service.create = function(obj){
console.log('Creating');
}
$scope.service.edit = function(obj){
console.log('Editing');
}
})
From the scope of FirstController, you can now call the function also available on the scope of SecondController:
<div ng-controller="FirstController">
<input type="checkbox" ng-model="button.type"> Toggle create/edit<br/>
<button ng-if="button.type" ng-click="service.create(obj)">Create</button>
<button ng-if="!button.type" ng-click="service.edit(obj)">Edit</button>
</div>
Demo
If you aren't reloading the page you can create an encapsulated variable in your service. Your set call would assign the value passed to that variable and your get call would return that variable to the caller.
One way I have achieved passing the data is to submit the form using the service and return a Json result to the service. Store the Json object in the encapsulated variable on the return and then pass a success or failure to the controller. When successful, let the controller redirect the view which will redirect using angular routing and ng-view. Once the new view, along with the new controller is loaded into the page, you can call the variable in your service to retrieve the data on the next controller.
Example Code:
app.factory('service', function ($q, $http) {
var savedData;
return {
loadData: function() {
return data;
},
search: function (parameters) {
var searchURL = '/MVCController/Search?parameter1=' + parameters.one +
'&parameter2=' + parameters.two;
var deferred = $q.defer();
$http.get(searchURL).success(function (data) {
savedData = data;
deferred.resolve(true);
}).error(function(data) {
data = 'An error occurred while searching: ' + data;
savedData = data //(if you want to save the error)
deferred.reject(data);
});
return deferred.promise;
}
}
});

Resources