Bind value to ng-init using ng-model - angularjs

I have one select field and one 'input' field,for both fields am getting data from database.selected option will be checked defaultly based on db value.When I change dropdown option, balance field will be auto populated.Now my problem is,balance field value is auto populating when I change dropdown. But by default balance field value is not auto populating for selected option.Whats wrong here?Html:
<form ng-app="myApp" ng-controller="myCtrl" ng-repeat="data in leaveDetails">
<div>
<label>Leave Type</label>
<select type="text" ng-model="selectedName" ng-init="selectedName=data.LeavetypeId" ng-options="data.id as data.Name for data in leaveTypes" ng-change="leaveBalance(selectedName)"></select>
</div>
<div>
<label>Availabe Leaves</label>
<input type="text" ng-init="balanceCount=data.Balance" ng-model="balanceCount">
</div>
</form>
Script:
<script>
var app=angular
.module('myApp', [])
.controller('myCtrl', function ($scope, $http) {
$scope.init = function () {
$scope.loadEditLevDetails();
}
$scope.loadEditLevDetails = function (id) {
$scope.Id = { leaveRequestId: id };
var requestHeaders = {
'content-type': 'application/json'
}
var httpRequest = {
method: 'post',
url: "/user/details",
headers: requestHeaders,
data: $scope.Id
}
$http(httpRequest).then(function (response) {
$scope.leaveDetails = response.data;
})
}
$scope.leaveBalance = function (selectedvalue) {
$scope.leaveTypeId = { leaveTypeId: selectedvalue };
var requestHeaders = {
"content-type": 'application/json'
}
var httpRequest = {
method: 'POST',
url: '/user/balanceCount',
headers: requestHeaders,
data: $scope.leaveTypeId
}
$http(httpRequest).then(function (response) {
$scope.noOfValues = response.data;
$scope.balanceCount = $scope.noOfValues[0].balance_count;
})
}
})
</script>

Here is the sample code to implement what you are trying to do!! Hope it would help!!
<!doctype html>
<html lang="en" data-ng-app="test">
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
<script type="text/javascript">
angular.module('test',[])
.controller('Main',function($scope)
{
$scope.myModel = {};
$scope.options = [{opt:'1'},{opt:'2'},{opt:'3'}];
});
</script>
</head>
<body ng-controller="Main">
{{'Select'}}
<select ng-model="myModel.options" ng-options="data.opt for data in options" ng-init="myModel.options=options[0]"></select>
{{myModel.options}}
</body>
</html>

Related

angularjs,I'm using ng-repeat loop option,value="number:1"

enter image description here
This situation causes the form submission parameter to become “number:1”。
Could you tell me why this problem happened?
javascript code as follows:
app.controller("Controller", function($scope,$http,$filter){
$http({
method:"POST",
url:"<%=request.getContextPath()%>/user.getUser",
params:{"name":name}
}).then(function successCallback(response) {
$scope.data = response.data;
}, function errorCallback(response) {
alert("00");
});
$http({
method:"POST",
url:"<%=request.getContextPath()%>/group.selectAll"
}).then(function successCallback(res) {
if(res != null && res != ""){
$scope.userGroups = res.data;
}
}, function errorCallback(response) {
alert("00");
});
}
jsp code as follows:
<select name="positionId" class="form-control"
ng-model="data.userGroup.GroupId" >
<option ng-repeat="p in userGroups" value="p.GroupId"
ng-value="{{p.GroupId}}">{{p.name}}
</option>
</select>
app.controller("Controller", function($scope,$http,$filter){
var userGroups={};
$http({
method:"POST",
url:"<%=request.getContextPath()%>/group.selectAll"
}).then(function successCallback(res) {
if(res != null && res != ""){
$scope.userGroups = res.data;
}
}, function errorCallback(response) {
alert("00");
});
$http({
method:"POST",
url:"<%=request.getContextPath()%>/user.getUser",
params:{"name":name}
}).then(function successCallback(response) {
//$scope.data = response.data;
$scope.userGroups.GroupId = "" + response.GroupId;
}, function errorCallback(response) {
alert("00");
});
}
After getting the values in the JS controller file, write dropdown list in the view page as below:
<select name="positionId" class="form-control"
ng-model="userGroups.GroupId" >
<option ng-repeat="p in userGroups" value={{p.GroupId}}>
{{p.name}}
</option>
</select>
If you want to set a particular value in a dropdown list to show while loading the dropdown then simply assign the value to the ng-model in the respective js controller file as below:
$scope.userGroups.GroupId = "" + response.GroupId; // based on your specific data
(Note: please check I have set ng-model as userGroups.GroupId and assigned userGroups={}; to initialize the userGroups to be used in the view page.)
Thanks.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.js"></script>
</head>
<body data-ng-app="role" data-ng-controller="fooController">
<select class="form-control"
ng-model="user.roles"
ng-options="role.id as role.name for role in roles"
required=""></select>
</body>
</html>
<script>
var app = angular.module('role', []);
app.controller('fooController', function($scope){
$scope.roles = [{id:0, name:"Select"},{id:1, name:"Administrator"}, {id:2, name: "Student"}];
$scope.user = {};
$scope.groupId = 1;
$scope.user.roles = $scope.roles[$scope.groupId].id ;
});
</script>
</html>

How can i execute angular script after onclick event

Here is my html code:
<div ng-app="myApp" ng-controller="customersCtrl">
<p id="druzyny"></p>
</div>
and then in angular script:
var app = angular.module('myApp', []);
document.getElementById("search1").onclick = app.controller('customersCtrl', function($scope, $http){
var place = document.getElementById("place").value;
var sel1 = document.getElementById("sel1").value;
var sel2 = document.getElementById("sel2").value;
var req = {
method: 'post',
url: 'findTournament',
headers: {
'Content-type': 'application/json'
},
data: {place: 'test'}
};
$http(req).then(function(response){
});
});
I`ve got button id="search1" and i want that angular execute only when i click this button, no automatically when page is reload, is it possible?
Thanks for answears
HTML:
<div ng-app="myApp" ng-controller="customersCtrl as customers">
<input data-ng-model="customers.place">
<input data-ng-model="customers.sel1">
<input data-ng-model="customers.sel2">
<button data-ng-click="customers.init()"></button>
</div>
JS:
angular.module('myApp', []);
angular
.module('myApp')
.controller('customersCtrl', function($scope, customersService){
var vm = this;
vm.init = function(){
customersService.findTournament({place: vm.place, sel1: vm.sel1, sel2: vm.sel2})
.then(function(res){});
};
});
angular
.module('myApp')
.service('customersService', function($http){
return {
findTournament: findTournament
};
function findTournament(data){
return $http.post('findTournament', data);
}
});

Angularjs: Cannot display array items using ng-repeat

I am using AngularJs to retrieve the data from ASP.Net Controller.
The Json data is retrieved from the server, but can't figure out why cannot display array items when using the ng-repeat:
var app = angular.module('Appp', []);
app.controller('metadataCtrl', function ($scope, $http) {
$scope.lookupItems = {};
$http({ method: 'GET', url: '/home/listvalues?listid=3' }).then(function (response) {
$scope.lookupItems = response;
console.log($scope.lookupItems);
},
function (error) { alert("error"); });
// console.log($scope.listItems);
});
<form name="myForm" ng-controller="metadataCtrl" class="my-form">
<div ng-repeat="item in lookupItems">
{{$index}}
{{item.ListValueID}}
</div>
</form>
The Json Retrieved from the server:
[{"ListValueID":13,"Translation":{"TranslationID":0,"Value":"Important","LanguageValues":{"ar":"مهم","en":"Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":14,"Translation":{"TranslationID":0,"Value":"Less Importance","LanguageValues":{"ar":"أقل أهمية","en":"Less Importance"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":15,"Translation":{"TranslationID":0,"Value":"Very Important","LanguageValues":{"ar":"كثير الأهمية","en":"Very Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0}]
The most likely issue (assuming that your app and controller are constructed and referenced properly) is that the object returned from the promise contains a .data property which actually holds your JSON data.
Try this:
$http({ method: 'GET', url: '/home/listvalues?listid=3' })
.then(function (response) {
$scope.lookupItems = response.data;
console.log($scope.lookupItems);
},
function (error) {
alert("error");
});
I think you just forgot to wrap your app with ng-app:
var app = angular.module('Appp', []);
app.controller('metadataCtrl', function ($scope, $http) {
$scope.lookupItems = {};
$scope.lookupItems = [{"ListValueID":13,"Translation":{"TranslationID":0,"Value":"Important","LanguageValues":{"ar":"مهم","en":"Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":14,"Translation":{"TranslationID":0,"Value":"Less Importance","LanguageValues":{"ar":"أقل أهمية","en":"Less Importance"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":15,"Translation":{"TranslationID":0,"Value":"Very Important","LanguageValues":{"ar":"كثير الأهمية","en":"Very Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0}];
console.log($scope.lookupItems);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="Appp">
<form name="myForm" ng-controller="metadataCtrl" class="my-form">
<div ng-repeat="item in lookupItems">
{{$index}}
{{item.ListValueID}}
</div>
</form>
</body>
You probably misspelled Appp. Make sure your module definition in your javascript:
var app = angular.module('App', []); //Changed to App from Appp
matches your app declaration in your html
<div ng-app="App">
...controller declaration...
...body.....
</div>

How to get AngularJS BLOB to Download PDF?

Hello everyone I am really new to developing with AngularJS and I am trying to figure out how to use BLOB to download a PDF locally to a machine. I already got it to work with a JSON and now I need a PDF. I have written some code but it doesn't seem to be working.
html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.center {
position: absolute;
left: 50%;
bottom: 50%;
}
.btn-purple {
background-color: rgb(97, 34, 115);
width: 100px;
}
</style>
<meta charset="UTF-8">
<title></title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="center" ng-controller="jsonController" ng-app="app">
<a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
<button type="button" class="btn btn-purple">{{fileName}}</button>
</a>
</div>
<div class="center" ng-controller="pdfController" ng-app="app">
<a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
<button type="button" class="btn btn-purple">{{fileName}}</button>
</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript-canvas-to-blob/3.1.0/js/canvas-to-blob.js"></script>
<script src="app.js"></script>
</body>
</html>
controller.js
var app = angular.module('app', []);
app.config(['$compileProvider', function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
}]);
app.controller('jsonController', function ($scope, $window, $http, $log) {
$http.get('data.json')
.success(function (info) {
var data = angular.toJson(info, true);
data = data.replace(/\n/g, "\r\n")
console.log(data)
var blob = new Blob([data], {type: "octet/stream"}),
url = $window.URL || $window.webkitURL;
$scope.fileUrl = url.createObjectURL(blob);
$scope.schemaName = "test"
$scope.fileName = $scope.schemaName + ".json"
})
});
app.controller("pdfController", function ($scope, $http, $log, $sce) {
$http.get('data.json' + $stateParams.id,
{responseType: 'arraybuffer'})
.success(function (response) {
var file = new Blob([(response)], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
});
Possible Try-
HTML:
<button ng-click="downloadPdf()" >Download PDF</button>
JS controller:
'use strict';
var app = angular.module('app')
.controller('ctrl', function ($scope, MathServicePDF) {
$scope.downloadPdf = function () {
var fileName = "file_name.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
ServicePDF.downloadPdf().then(function (result) {
var file = new Blob([result.data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
};
});
JS services:
app.factory('ServicePDF', function ($http) {
return {
downloadPdf: function () {
return $http.get('api/my-pdf', { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
};
});
Happy Helping!
Tested with large files (> 1.5 GB) on
Firefox 56.0
Safari 11.0
Use the following in your angular controller:
$scope.download = function() {
$http({
method: 'GET',
url: fileResourceUrl,
responseType: 'blob'
}).then(function(response) {
var blob = response.data;
startBlobDownload(blob, "largedoc.pdf")
});
};
function startBlobDownload(dataBlob, suggestedFileName) {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
// for IE
window.navigator.msSaveOrOpenBlob(dataBlob, suggestedFileName);
} else {
// for Non-IE (chrome, firefox etc.)
var urlObject = URL.createObjectURL(dataBlob);
var downloadLink = angular.element('<a>Download</a>');
downloadLink.css('display','none');
downloadLink.attr('href', urlObject);
downloadLink.attr('download', suggestedFileName);
angular.element(document.body).append(downloadLink);
downloadLink[0].click();
// cleanup
downloadLink.remove();
URL.revokeObjectURL(urlObject);
}
}
Change your responseType from responseType: 'arraybuffer'
to responseType: 'blob'
In you controller PHP
return $pdf->stream();
In you controller AngularJS
$http.post('generate', {
dateStart: $scope.ds,
dateEnd: $scope.de
},
{
responseType: 'arraybuffer'
}).then(function success(response) {
var blob = new Blob([response.data], { type: "application/pdf"});
saveAs(blob, "filename.pdf");
}, function error(error) {
$scope.recordErrors(error);
});
This code worked for me in angular 9, Yii2, while using mpdf
this._gService.download_post(`controller/action`, postData).pipe(takeUntil(this._unsubscribeAll)).subscribe(result => {
const fileURL = URL.createObjectURL(result);
// Direct print preview
// const iframe = document.createElement('iframe');
// iframe.style.display = 'none';
// iframe.src = fileURL;
// document.body.appendChild(iframe);
// iframe.contentWindow.print();
// Direct Download
const fileName = 'Patient Report';
const a = document.createElement('a');
document.body.appendChild(a);
a.href = fileURL;
a.download = fileName;
a.click();
}, error => {
// show error message
});

Ionic/AngularJS & Wordpress API

I'm somewhat new to the JS world, so I'm struggling a bit as to what I did wrong. My sample data from wordpress API is not working. Any ideas what I did wrong:
app.controller('FeedCtrl', function($http, $scope, $ionicLoading) {
console.log("Loading FeedCtrl");
$scope.stories = [];
function loadStories(params, callback) {
$http.get('http://public-api.wordpress.com/rest/v1/freshly-pressed/', {params: params})
.success(function(response) {
var stories = [];
angular.forEach(response.data.children, function(child) {
stories.push(child.data);
});
callback(stories);
});
}
$scope.loadOlderStories = function() {
var params = {};
if ($scope.stories.length > 0) {
params['after'] = $scope.stories[$scope.stories.length - 1].name;
}
loadStories(params, function(olderStories) {
$scope.stories = $scope.stories.concat(olderStories);
$scope.$broadcast('scroll.infiniteScrollComplete');
});
};
$scope.loadNewerStories = function() {
var params = {'before': $scope.stories[0].name};
loadStories(params, function(newerStories) {
$scope.stories = newerStories.concat($scope.stories);
$scope.$broadcast('scroll.refreshComplete');
});
};
I've made a simplified example with your data.
Click the 'Load more' button to retrieve some posts. You should see a list with the title and the author of a post.
EDIT: There appears to be some cross-domain request issues, that's why the 'Load stories' button won't work. Just try to reflect this code inside your controller, it should work.
var app = angular.module('myApp', []);
app.controller('feedCtrl', function ($scope, $http) {
$scope.stories = [];
$scope.loadStories = function loadStories() {
console.log('loading stories');
$http.get('http://public-api.wordpress.com/rest/v1/freshly-pressed/')
.then(function onSuccess(response) {
console.log(response);
$scope.stories = response.data.posts;
}, function onFailed(error) {
console.error('Error:', error)
});
}
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="feedCtrl">
<button data-ng-click="loadStories()">Load stories</button>
<ul>
<li data-ng-repeat="story in stories">Title: {{ story.title }} - {{ story.author.first_name }} {{ story.author.last_name }}</li>
</ul>
</div>
</body>
</html>
Normally we wouldn't handle $http calls in our angular.controller. This needs to be done in an angular.service.

Resources