ng-option's default ng-model value using a Factory/Service - angularjs

As a new AngularJS user I have a form that populates with data as follows,
My EntriesFactory.js,
(function () {
"use strict";
var EntriesFactory = function ($http) {
var factory = {};
//Get Full List
factory.getEntries = function () {
return $http.get('ABC/XYZ.cfc?method=GetFullList&returnformat=json&queryformat=struct');
};
return factory;
};
EntriesFactory.$inject = ['$http'];
angular.module('appDHCP')
.factory('EntriesFactory', EntriesFactory);
}());
populates EntryDetails.cfm form
<form class="form-horizontal" ng-repeat="detail in entry">
<div class="form-group">
<h2 class="col-sm-2">Entry Details</h2>
</div>
</div>
<div class="form-group">
<label for="Description" class="col-sm-2 control-label">Description</label>
<div class="col-sm-4">
<input type="text" class="form-control" placeholder="{{detail.DESCRIPTION}}" value="{{detail.DESCRIPTION}}">
</div>
</div>
<div class="form-group">
<label for="Lab" class="col-sm-2 control-label">Lab/PI</label>
<div class="col-sm-4">
<select ng-model="???" ng-options="lab.LABIS for lab in labs"></select>
</div>
</div>
</form>
in here labs are retrieved from WistarService.js,
(function () {
"use strict";
var WistarService = function ($http) {
this.getLabs = function () {
return $http.get('ABC/XYZ.cfc?method=GetLabs&returnformat=json&queryformat=struct');
};
};
WistarService.$inject = ['$http'];
angular.module('appDHCP')
.service('WistarService', WistarService);
}());
Finally, here is my EntryDetailsController.js
(function () {
"use strict";
var EntryDetailsController = function ($scope, $routeParams, EntriesFactory, WistarService) {
var addressId = $routeParams.REC_ID;
$scope.entry = null;
$scope.labs = null;
//function init() {
EntriesFactory.getEntry(addressId)
.success(function (entry) {
$scope.entry = entry;
})
.error(function (data, status, headers, config) {
//handel errors
});
WistarService.getLabs()
.success(function (labs){
$scope.labs = labs;
})
.error(function (data, status, headers, config) {
//handel errors
});
/*
}
init();
*/
};
EntryDetailsController.$inject = ['$scope', '$routeParams', 'EntriesFactory', 'WistarService'];
angular.module('appDHCP')
.controller('EntryDetailsController', EntryDetailsController);
}());
What I want is, select to have {{detail.LAB}} value selected by default and have values in labs as other options.
Any help is greatly appreciated.

Once you get all the labs from service, on the scope you need to set the details.LAB variable manually which should point to an element from labs array.
WistarService.getLabs()
.success(function (labs){
$scope.labs = labs;
$scope.details.LAB= labs.filter(function(){ // some condition to filter})[0];
})
The ng-model points to details.LAB.
Update: Based on your comment the there should be some key to match labs to entry. Therefore you should do something like
$scope.details.LAB= labs.filter(function(lab){
lab.id=$scope.entry.id;
)[0];
But remember you can only do this once the entry data is available. So either chain the http operations or put a watch on entry and add that logic in the watch.

Related

Save the value of a service in a variable

I must fill a combo to be able to select the value that the user wanted I have managed to do this with the data stored in an array, the next step is to consult a service and use the return values
<html>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="text">ObjectType:</label>
<input type="text" ng-model="type" ng-keyup="complete(type)" class="form-control" placeholder="Search"/>
<ul class="list-group">
li class="list-group-item" ng-repeat="data in filterType" ng-click="fillTextbox(data)">{{data}}</li>
</ul>
</div>
</div>
</html>
var app = angular.module("Trace", []);
app.controller('TraceControlles', function ($scope, $http) {
//$scope.typeList = ["integration", "none"];
$scope.typeList = [];
$scope.loadTypes = function () {
$http.get("/api/Trace/GetObjectType")
.then(function (responce) {
$scope.typeList = responce.data;
}, function errorCallback(responce) {
});
}
$scope.complete = function (string) {
var output = [];
angular.forEach($scope.typeList, function (type) {
if (type.toLowerCase().indexOf(string.toLowerCase()) >= 0) {
output.push(type);
}
});
$scope.filterType = output;
}
$scope.fillTextbox = function (string) {
$scope.type = string;
$scope.filterType = null;
}
});
146/5000
When running the web api the service return values are not loaded, the browser does not mark any syntax error or anything like that.

mvc angularjs autocomplete

I am trying to implement textbox autocomplete functionality in MVC angularjs. I have see examples with angucomplete method but it gets all db values in one shot. When I hit the key back again it doesnt go to MVC controller action.
Below is my code view code:
<div ng-controller="sampleController">
<div ng-app="medAapp" ng-controller="sampleController">
<div angucomplete-alt id="txtautocomplete" placeholder="Type Country name" pause="100" selected-object="AfterSelectedCoutries" local-data="countries" search-fields="Country" title-field="Country" minlength="1" input-class="form-control" match-class="highlight">
</div>
<div ng-show="SelectedCountries">
Selected Country: {{SelectedCountries.Country}}
</div>
</div>
</div>
Module code:
var medApp = angular.module("medApp", ['angucomplete-alt', 'ui.grid', 'ui.grid.pagination', 'ui.grid.selection', 'ui.grid.exporter',
'ui.grid.grouping', 'ui.grid.expandable']);
Angular Controller code:
medApp.controller("sampleController", ['$scope', '$http', function ($scope, $http) {
$scope.countries = [];
$scope.SelectedCountries = null;
$scope.AfterSelectedCoutries = function (selected) {
if (selected) {
$scope.SelectedCountries = selected.originalObject;
}
}
$http.get("/Home/GetCountry").then(function (d) {
$scope.countries = d.data;
}, function (error) {
alert('Failed');
})
}])
MVC Controller code:
public JsonResult Getcountry()
{
List<Item> listcountry = new List<Item>()
{
new Item()
{
Id=1,
Name= "Crocin"
},
new Item()
{
Id=2,
Name= "Bruffen"
}
};
return Json(listcountry, JsonRequestBehavior.AllowGet);
}
My question is GetCountry method should have a parameter to get the required records but in none of the samples it does.
Any suggestions??
Thanks

Angularjs checkbox initialization issue using json object

So i have a checkbox page barely working, the issue is when i first start this page, the checkbox is not checked, even though i try to initialize it from backend node server. No error in browser debugger though.
in the server mye,
app.get('/2getMyDiagValue', function(req, res)
{
console.log("get my diag");
var formDataArray = { "formDataObjects": [
{"flagName":"myStuff1", "flagVal":0},
{"flagName":"myStuff2", "flagVal":1}
]};
res.contentType('application/json');
res.send(formDataArray);
});
app.post('/2setMyDiagValue', function(req, res)
{
......
}
in the client mye,
app.controller('myDiagController', function($scope, $http, $routeParams, QueryMyService) {
$scope.message = 'SID Diagnostics';
// using http.get() to get existing my setting from server mye
QueryMyService.getInfoFromUrl7('/2getMyDiagValue').then(function(result) {
$scope.formData = result.formDataObjects;
}, function(error) {
alert("Error");
} );
$scope.submitForm = function() {
console.log("posting form data ...");
$http.post("/2setMyDiagValue",
JSON.stringify($scope.formData)).success(function(){} );
};
});
app.factory('QueryMyService', function($http, $q, $location) {
var factory = {};
var browserProtocol = 'http';
var port = ':1234';
var address = 'localhost';
var server = browserProtocol + '://' + address;
//////////////////////////////////////////////////////////
factory.getInfoFromUrl7 = function(myUrl) {
var deferred = $q.defer();
$http.get(myUrl).success(function(data) {
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
}
return factory;
}
checkbox webpage itself
<form ng-submit="submitForm()" ng-controller="myDiagController">
<div class="control-group" style="color:black">
<label>My Checkbox</label>
<div class="checkbox">
<label class="checbox-inline" >
<input class="big-checkbox" type="checkbox" ng-model="formData.myStuff1"
ng-true-value="1" ng-false-value="0" ng-checked="formData.myStuff1 == 1">
<h4>Message 1</h4>
<input class="big-checkbox" type="checkbox" ng-model="formData.myStuff2"
ng-true-value="1" ng-false-value="0" ng-checked="formData.myStuff2 == 1">
<h4>Message 2</h4>
</label>
</div>
<br>
<input class="btn-primary" type="submit">
</form>
i did try to modify ng-checked like this and the checkbox did show checked.
ng-checked="true"
well, just used "res.json" in the node.js side and made it work, guess i just don't have time to learn, while this fxxking company gave me a tough schedule

Display dropdown on tick of checkbox

// I have written java code to fetch data from mongo-db. What i need to do is on tick of checkbox button i have to display those data in drop-down menu using angular-js and bootstrap. Nothing is happening after doing these code.
.html page
<div ng-controller="release">
<div class="col-md-2 col-centered col-fixed">
<label for="cloneRelease" translate="release.form.cloneRelease">CloneRelease</label>
</div>
<div>
<input type="checkbox" ng-model="ticked">
<div class="dropdown-menu" ng-repeat="release in releaseName" ng-show="ticked">{{release.name}}</div>
</div>
</div>
controller.js
releaseApp.controller('release', function($scope, $location, $http, ReleaseNameService){
$scope.releaseName = [];
init();
function init(){
ReleaseNameService.getReleaseName().then(function(data){
$scope.releaseName = data;});
console.log('inside controller: '+$scope.releaseName);
}
});
service.js
releaseApp.factory('ReleaseNameService', function($http){
var releaseName = [];
var factory = {};
factory.getReleaseName = function(){
return $http.get('release/fetchAllReleaseDetails').then(function(response){
releaseName = response.data;
console.log('inside service method'+ releaseName);
return releaseName;
});
};factory;
});
It is simple, u need to bind checkbox with ng-model:
<input type="checkbox" ng-model="ticked">
If its ticked $scope.ticked return true, else return false. If true show data, if false hide it (with ng-show)
Here is an example in jsFiddle without css ofc.
http://jsfiddle.net/RLQhh/2282/
UPDATE:
recreateing case with service.
service.js
app.factory('dataService', function ($http) {
var dataObject= {
async: function () {
var promise = $http.get('data/').then(function (response) {
return response;
});
return promise;
}
};
return dataObject;
})
controller.js
$scope.dataTest = [];
$scope.ticketed = false;
var getData = function(){
dataService.async().then(function (d) {
$scope.dataTest = d.data;
});
}
getData();
html
<input type="checkbox" ng-model="ticketed">
<div ng-show="ticketed" ng-repeat="dat in dataTest">
{{dat.name}}
</div>
...this is tested case so it should work with yours
You can make a REST call to fetch the data from your java function and store it in scope.Then you can use ng-repeat to display data in dropdown.
Here is a very good article on how to do it.
http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/06/29/how-to-work-with-the-bootstrap-dropdown-in-angularjs.aspx

Using $rootscope to change ng-show between controllers

What I want to do is pretty simple. I have two forms. One form is visible in the beginning and once that form is submitted it dissappears and the second form appears. I am trying to use a flag variable set at $rootscope.showFlag but it doesn't seem to work.
Here is my HTML part:
<div ng-app="myapp" >
<div class="container" ng-controller="addItemController" ng-show="showFlag">
<form class="form-signin">
<h2 class="form-signin-heading">Add an item</h2>
<input type="text" name="itemName" ng-model="myForm.itemName" id="inputItemName" class="form-control" placeholder="Name of the item" autofocus required>
<button class="btn btn-lg btn-primary btn-block" ng-click="myForm.submitTheForm()">Add item</button>
</form>
</div> <!-- /container -->
<div class="container" ng-controller="MyCtrl" ng-show="!showFlag">
<input type="text" ng-model="username"></br></br>
<button class="btn btn-lg btn-primary btn-block" ngf-select ng-model="files">Select file</button>
</div>
</div>
And this is my Angular app:
var app = angular.module("myapp", ['ngFileUpload'])
.run(function($rootScope) {
$rootScope.showFlag = true;
});
app.controller("addItemController", function($rootScope, $scope, $http) {
$scope.myForm = {};
$scope.showFlag = true;
Data.Show = 10;
$scope.myForm.submitTheForm = function(item, event)
{
console.log("--> Submitting form");
var dataObject = {
itemName : $scope.myForm.itemName,
};
var responsePromise = $http.post("/angularjs-post", dataObject, {});
responsePromise.success(function(dataFromServer, status, headers, config) {
console.log(dataFromServer.title);
//alert("Submitting form OK!");
$rootScope.showFlag = false;
});
responsePromise.error(function(data, status, headers, config) {
alert("Submitting form failed!");
});
}
$scope.myForm.uploadPhoto = function(item, event)
{
console.log('Uploading photo');
}
});
app.controller('MyCtrl', ['$scope', 'Upload', function ($rootScope, $scope, Upload) {
$scope.$watch('files', function () {
$scope.upload($scope.files);
});
$scope.log = '';
$scope.upload = function (files) {
if (files && files.length) {
var file = files[0];
Upload.upload({
url: '/upload',
fields: {
'username': $scope.username
},
file: file
}).progress(function (evt) {
// during progress
}).success(function (data, status, headers, config) {
// after finishing
});
}
};
}]);
You set showFlag to true in two places.
In the root scope.
.run(function($rootScope) {
$rootScope.showFlag = true;
});
And in the local scope.
app.controller("addItemController", function($rootScope, $scope, $http) {
$scope.myForm = {};
$scope.showFlag = true;
As the ng-show for the first form looks in the local scope first it won't be affected even when you set the rootScope flag to false.
One possible reason could be that you have misspelled the controller name
it should be addSellItemController.
<div class="container" ng-controller="addSellItemController" ng-show="showFlag">
Another small mistake is you have not added $rootScope as a dependency in your MyCtrl directive.
app.controller('MyCtrl', ['$rootScope','$scope', 'Upload', function ($rootScope, $scope, Upload) {
...
});

Resources