basic $scope connection with model - angularjs

Its my code:
.controller("GetAllAuthors", function ($scope, $http) {
$http.get('http://localhost:8080/authors')
.then(function (response) {
$scope.authors = response.data;
});
$scope.edit = function (index) {
for (var i = 0; i < $scope.authors.length; i++) {
if ($scope.authors[i].id == index) {
$scope.object = $scope.authors[i];
break;
}
}
}
})
Html view:
<tbody ng-repeat="author in authors">
<td><input type="button" ng-click="edit(author.id)" value="Edit"/></td>
<div ng-controller="GetAllAuthors">
{{object.id}} // <--- doesn't display it
</div>
It's not working. I can't use date binding with my object. How fix it?

You need to put http inside edit method.
.controller("GetAllAuthors", function ($scope, $http) {
$scope.edit = function (index) {
$http.get('http://localhost:8080/authors')
.then(function (response) {
$scope.authors = response.data;
for (var i = 0; i < $scope.authors.length; i++) {
if ($scope.authors[i].id == index) {
$scope.object = $scope.authors[i];
break;
}
}
});
}
})

Try this
Initialize $scope.object outside the function.

Related

Angularjs multiple file upload in single request

<input type="file" ng-model="item.files" ng-change="item.onSelectFile()"/>
function MyController($scope, httpSrvc){
function Item(){
this.name = "";
this.files = [];
this.onSelectFile = function(file){
if(this.files.length < 3){
this.files.push(file);
}
}
this.onSubmit = function(){
let formData = new FormData();
formData.append("name",this.name);
for(let i = 0 ; i < this.files.length ; i++){
formData.append(`page_${i+1}`,this.files[i]);
}
httpSrvc.post(url,formData)
.then(function(res){console.log(res)})
.catch(function(err){console.log(err)})
}
}
function init(){
$scope.item = new Item();
}
}
is it possible to store file in a array? what value should I set to ng-model?
Check following code.
Points to note :
You need to attach onchange event and get the scope with angular.element(this).scope()
You need to wrap your code inside $scope.$apply. This is required if you want to display the list of files on the view. This is necessary since the files array is not tracked by angular since it is not assigned as ng-model.
'Content-Type': undefined is required in the http headers
angular.module('myApp', []).controller('MyController', ['$scope', '$http',
function MyController($scope, $http) {
function Item() {
this.name = "";
this.files = [];
this.onSelectFile = function(event) {
$scope.$apply(() => {
let file = event.target.files[0];
if (this.files.length < 3) {
this.files.push(file);
}
});
}
this.onSubmit = function() {
let formData = new FormData();
formData.append("name", this.name);
for (let i = 0; i < this.files.length; i++) {
formData.append(`page_${i+1}`, this.files[i]);
}
let url = "www.google.com";
let request = {
method: 'POST',
url: url,
data: formData,
headers: {
'Content-Type': undefined
}
};
$http(request)
.then(function(res) {
console.log(res)
})
.catch(function(err) {
console.log(err)
})
}
}
function init() {
$scope.item = new Item();
}
init();
document.querySelector('input[type="file"]').addEventListener('change', (event) => $scope.item.onSelectFile(event));
}
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<input type="file" ng-model="item.file" />
<ul>
<li ng-repeat="file in item.files">
{{ file.name }}
</li>
</ul>
<input type="button" value="Submit" ng-click="item.onSubmit()">
</div>

Showing dynamic content inside ngRepeat

Struggling to show dynamic content inside a ngRepeat. When it comes time to show my promise content, I'm getting an empty object {}:
<div ng-controller="DemoCtrl">
<div class="sidebar" ng-repeat="row in rows">
<div class="row">
<input type="checkbox">
<div class="name">{{row.name}}</div>
<div class="title">{{map[$index]}}</div>
</div>
</div>
</div>
and the controller:
function DemoCtrl($scope, $http, $q) {
const rows = function() {
const rows = [];
for (let i = 0; i < 12; i++) {
rows.push({
id: `demo-${i}`,
name: `Demo ${i}`
});
}
return rows;
};
$scope.rows = rows();
$scope.map = [];
// $scope.$watch($scope.map, function (oldValue, newValue) {
// console.log(oldValue, newValue);
// });
function _data() {
// const promises = [];
for (let i = 0; i < $scope.rows.length; i++) {
var defer = $q.defer();
$http.get(`https://jsonplaceholder.typicode.com/posts/${i + 1}`).then(function(post) {
defer.resolve(`${post.data.title.substring(0, 10)}...`);
});
$scope.map.push(defer.promise);
// promises.push(defer.promise);
}
// return $q.all(promises);
return $q.all($scope.map);
}
function _init() {
_data().then(function(data) {
$scope.map = data; // why aren't we getting here?
});
};
_init();
}
Plunker here: https://plnkr.co/edit/2BMfIU97Moisir7BBPNc
I've tinkered with some other ideas such as trying to add a $watch on the $scope object after the value changes, but I'm not convinced this will help in any way. Some lingering questions I have:
From what I understand, you can use a promise inside a template so how/why does this change inside a ngRepeat?
Why isn't my callback for $q.all getting called?
If this is not the right approach, what is?
In Angular you will almost never need to use $q.
You can simply fill an array of posts titles after each $http.get
function DemoCtrl($scope, $http) {
const rows = function () {
const rows = [];
for (let i = 0; i < 12; i++) {
rows.push({
id: `demo-${i}`,
name: `Demo ${i}`
});
}
return rows;
};
$scope.rows = rows();
$scope.map = [];
function _init() {
for (let i = 0; i < $scope.rows.length; i++) {
$http.get(`https://jsonplaceholder.typicode.com/posts/${i + 1}`).then(function (post) {
$scope.map.push(post.data.title);
});
}
}
_init();
}
https://plnkr.co/edit/zOF4KNtAIFqoCOfinaMO?p=preview

Why Angular js Service does not work?

I wrote script to test passing variables between controllers, so i define a service and declare variable on it getContents, then pass it to next controller personController, but something goes wrong, this is my script:
<script>
angular.module("app", []).service("personService", function () {
var getContents = {};
})
.controller("personController", function ($http, $scope, personService) {
$scope.GetContents = function () {
$http.get("/Home/Get").success(function (data) {
debugger;
personService.getContents = data;
$scope.Persons = data;
});
}
$scope.Save = function () {
$http.post("AddPerson",$scope.model).success(function (status) {
debugger;
console.log('status =', status);
$scope.ShowForm = false;
$scope.GetContent();
});
}
$scope.AddPerson = function () {
$scope.ShowForm = true;
$scope.model = {};
}
});
</script>
what is wrong?
NOTE: when i remove the Service, the controller work properly and get data from /Home/Get.
Edit: this is my edit:
<script>
angular.module("app", []).service("personService", function () {
var Content = {};
return {
getContent: function () {
return Content;
},
setContent: function (value) {
Content = value;
}
};
})
.controller("personController", function ($http, $scope, personService) {
$scope.GetContents = function () {
debugger;
$http.get("/Home/Get").success(function (data) {
debugger;
console.log("successData :", data); //console did not log
personService.setContent(data);
console.log("ServiceData:",personService.getContent()) //console did not log too
$scope.Persons = data;
});
}
$scope.AddPerson = function () {
$scope.ShowForm = true;
$scope.model = {};
}
});
</script>
and this is my html:(for more help)
<div ng-app="app">
<div class="container" ng-controller="personController" ng-init=" GetContent()">
<div ng-show="!ShowForm">
<table class="table">
<thead>
<tr>
<th>Firstname</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in Persons">
<td>{{person.Name}}</td>
</tr>
</tbody>
</table>
</div>
</div>
you have to return service
service
angular.module("app", []).service("personService", function () {
var content = {};
var person = {
setContent :function(item){
content = item;
}
getContent : function(){
return content;
};
};
return person;
})
Controller
.controller("personController", function ($http, $scope, personService) {
$scope.GetContents = function () {
$http.get("/Home/Get").success(function (data) {
debugger;
personService.setContent(data); // set content to service..
$scope.Persons = data;
});
}
$scope.Save = function () {
$http.post("AddPerson",$scope.model).success(function (status) {
debugger;
console.log('status =', status);
$scope.ShowForm = false;
personService.getContent(); // get content from service..
});
}
$scope.AddPerson = function () {
$scope.ShowForm = true;
$scope.model = {};
}
define personService.getContent() to $scope variable to display on view page.
$scope.content = personService.getContent();

AngularJS custom filter don't receive data

I have a problem with a new filter which don't receive the data:
here my error log:
Controller Code:
angular.module('reklaApp')
.controller('MainCtrl', function ($scope, $http, Reklas, Modal) {
$scope.newRekla = {};
Reklas.getAll()
.success(function(data) {
$scope.reklas = data;
});
Filter Code:
angular.module('reklaApp')
.filter('dateFilter', function () {
return function (items) {
var filtered = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
filtered.push(item);
}
return filtered;
};
});
HTML Code:
<tr ng-repeat="rekla in reklas | dateFilter">
<td>{{rekla.dt | date: 'dd.MM.yyyy'}}</td>
<td>{{rekla.order}}</td>
<td>{{rekla.personal}}</td>
<td>{{rekla.department}}</td>
<td>{{rekla.xyz}}</td>
<td>{{rekla.desc | limitTo: '50'}}</td>
<td>{{rekla.costs}}</td>
I think the "item" variable dont receive the data from the ng-repeat!?
It's because you didn't create it to begin with on your $scope. So since your getAll function takes some time the filter doesn't have the data. You can fix this two ways:
By first initializing the variable:
angular.module('reklaApp')
.controller('MainCtrl', function ($scope, $http, Reklas, Modal) {
$scope.newRekla = {};
$scope.reklas = [];
Reklas.getAll()
.success(function(data) {
$scope.reklas = data;
});
Or by updating your filter:
angular.module('reklaApp')
.filter('dateFilter', function () {
return function (items) {
if(!angular.isArray(items)){ return items }
var filtered = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
filtered.push(item);
}
return filtered;
};
});

Load data to dropdown in angularjs

I am new to this angular js.
In my code a dropdown control has been loaded with some items, i know this list should be loaded from a xml file.
I want to know where/how it is been coded to load the data. Check this code and help me...
<select size="10" ng-model="model.addSelection" ng-options="a.name for a in availableList | availableList | propertyFilter:model.availableFilter" class="listBoxStyle" wat-focus/>
angular.module('readbackSelectModule', [])
.filter('availableList', [
function () {
return function (input) {
if (!angular.isArray(input)) return input;
var out = [];
for (var i = 0; i < input.length; i++) {
if (input[i].visible == true)
out.push(input[i]);
}
return out;
}
}
])
.filter('plotList', [
function () {
return function (input) {
if (!angular.isArray(input)) return input;
var out = [];
for (var i = 0; i < input.length; i++) {
if (input[i].visible == false)
out.push(input[i]);
}
return out;
}
}
])
.controller('readbackSelectCtrl', ['$scope', '$modalInstance', 'generalDataService', 'keyService', 'propertyFilterFilter', 'availableListFilter', 'plotListFilter', 'plotPanelService',
function ($scope, $modalInstance, generalDataService, keyService, propertyFilterFilter, availableListFilter, plotListFilter, plotPanelService) {
var CANCEL_MESSAGE = 'cancel';
var GET_DATA_MESSAGE = 'getdata';
var REQUEST_PROPERTY_LIST_MESSAGE = 'requestplotdata';
var SUBSCRIBE = 'plotsubscribe';
var UNSUBSCRIBE = 'plotunsubscribe';
var STREAM_TYPE = '4';
$scope.model = {};
$scope.model.addSelection;
$scope.model.removeSelection;
$scope.model.availableFilter;
// List of properties
$scope.availableList = [];
};
Use Angular's $http service.
You can do it in your readbackSelectCtrl, like this:
...
$scope.model = {};
$scope.model.addSelection;
$scope.model.removeSelection;
$scope.model.availableFilter;
$http.get(/** insert XML file URL here **/)
.success(function(data) {
// process the data and extract the XML elements you want
$scope.availableList = xmlExtractedArray;
})
.error(function(err) {
// handle error
});
Check this plunker for a working demo.

Resources