I am trying to populate a text area with a formatted letter, which comes from a text file. This text file contains objects like {{client.name}} and {{client.address}}, which I would like to replace with the value of the specific client's attribute. Here is the code I have this far,
$scope.loadFlyer = function() {
$http.get("/assets/clientwelcome.txt").then(function(res){
$scope.flyerdescription = res.data;
$scope.flyerdescription = $scope.flyerdescription.replace(/{{client.name}}/g, $scope.client.name);
});
};
Where previously I had called the data from the client's table:
myApp.controller('ClientCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
$scope.clients = [];
$http.get('/client').success(function(data, status, headers, config) {
$scope.clients = data;
if (data == "") {
$scope.clients = [];
}
}).error(function(data, status, headers, config) {
console.log("Ops: could not get any data");
});
And this is the field that I am trying to populate:
<div class="form-group">
<label class="control-label" for="flyer-description">Description</label>
<textarea style="height:400px" class="form-control" id="flyer-description" ng-model="flyerdescription"></textarea>
</div>
Unfortunately, no replacing is done. I've tried to format the replace as I have seen in the javascript documents, but to no avail.
Editted* per discussion below
You have a list of clients that looks like [{name: 'Hank Aaron'}, {name: 'Sandy Koufax'}, {name: 'Bo Jackson'}], and a template string, that contains a value: '{{client.name}}', that you want to replace with a name from your clients list.
myApp.controller('ClientCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
$scope.clients = [];
$http.get('/client').success(function(data, status, headers, config) {
$scope.clients = data;
if (data == "") {
$scope.clients = [];
}
}).error(function(data, status, headers, config) {
console.log("Ops: could not get any data");
});
$scope.loadFlyer = function() {
$http.get("/assets/clientwelcome.txt").then(function(res){
$scope.flyerdescription = res.data;
$scope.descriptions = [];
for(var i=0; i<$scope.clients.length; i++){
$scope.descriptions[i].push($scope.flyerdescription.replace(/{{client.name}}/g,$scope.clients[i].name));
}
});
};
}]);
and in your HTML
<div class="form-group">
<div ng-repeat="description in descriptions">
<label class="control-label" for="flyer-description">Description</label>
<textarea style="height:400px" class="form-control" id="flyer-description" ng-model="description"></textarea>
</div>
</div>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="demoApp" ng-controller="validationCtrl" class="form-group">
<label class="control-label" for="flyer-description">Description</label>
<textarea style="height:100px" class="form-control" id="flyer-description" ng-model="stringname
"></textarea>
</div>
<script>
//This is controller
var app = angular.module('demoApp', []);
app.controller('validationCtrl', function($scope) {
$scope.stringname = 'angular123456 test demo';
$scope.stringname = $scope.stringname.replace('test', "");
});
</script>
</body>
</html>
Related
Hi I am new to Angularjs. I am trying to create a typeahead where I am fetching the data through the api. I tried searching for the solution but I dint get the solution what I was looking for. Below is the code what I have done so far.
HTML CODE:
<div ng-controller="newController">
<div class="selection-box">
<div class="title-box">
<div class="search_item">
<input name="document" ng-model='query' type="text" typeahead="document as document.name for document in documents | filter:query | limitTo:8" id='document' placeholder="SEARCH FOR YOUR DOCUMENT" class="search_box">
</div>
{{query}}
</div>
</div>
</div>
In this input box whatever I type it gets printed in the {{query}} but doesn't show any data fetching from the api. I am using bootstrap ui . Below is the controller what I wrote.
newController.js:
var myApp = angular.module('myModule', ['ui.bootstrap']);
myApp.service("searchService", function ($http) {
var apiUrl = "http://12.56.677/api/v1/mobile/";
var apiKey = "123nm";
this.searchDocument = function(query) {
var response = $http({
method: 'post',
url: apiUrl + "search",
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
params: {
key: apiKey,
query: query
}
});
return response;
};
});
myApp.controller('newController', ['$scope', 'searchService' , function($scope, searchService, $rootScope, $http, $window, $document) {
var apiUrl = "http://12.56.677/api/v1/mobile/";
var apiKey = "123nm";
url = apiUrl + "search";
Key = apiKey;
$scope.query = undefined;
console.log(query);
searchService.searchDocument(query='').then (function (res) {
if(res.data.status == "OK")
{
$scope.documents = res.data.result;
console.log($scope.documents);
// var userinformation = res.data.result;
// $window.localStorageService.setItem('searchDocument', JSON.stringify(query));
}
else {
$scope.errorMessage = res.data.message;
}
})
}])
Any help would be appreciated.
What you attempted to do is using typeahead with a pre-fetched list (an with an empty query).
You probably want to do asynchronous search and would need a data fetch function to do so.
HTML, note the typeahead expression:
<input name="document" ng-model='query' type="text"
typeahead="document as document.name for document in (getDocuments() | limitTo:8)"
id='document'
placeholder="SEARCH FOR YOUR DOCUMENT" class="search_box">
Controller:
myApp.controller('newController', ['$scope', 'searchService' , function($scope, searchService, $rootScope, $http, $window, $document) {
var apiUrl = "http://12.56.677/api/v1/mobile/";
var apiKey = "123nm";
// What are these two undeclared variables lying here around for?
url = apiUrl + "search";
Key = apiKey;
$scope.getDocuments = function(query){
searchService.searchDocument(query) // Check your API, I am not sure how you're API treats these parameters
.then (function (res) {
if(res.data.status == "OK")
{
var documents = res.data.result;
console.log(documents);
return documents;
}
else {
$scope.errorMessage = res.data.message;
return [];
}
})
}
}])
I think you need to return promise from the searchService.searchDocment() as below:
return searchService.searchDocument(query='').then(......)
//HTML
<input name="document"
ng-model='query' type="text"
uib-typeahead="document as document.name
for document in documents |filter:query | limitTo:8" id='document'
placeholder="SEARCH FOR YOUR DOCUMENT" class="search_box">
//Controller
searchService.searchDocument('').then (function (res) {
if(res.data.status == "OK"){
$scope.documents = res.data.result;
}
else {
$scope.errorMessage = res.data.message;
}
});
I used Spring framework as a back-end and angular as a front end. When I try to insert data from the angualrJs value is inserted into database but display error code. please suggest me what is the wrong in this code.
var app = angular.module("categoryApp", []);
app.controller('submitCategory', [ '$scope', '$http',
function($scope, $http) {
$scope.submitClick = function() {
var dataObj = {
name : $scope.name
};
var result = $http.post("/tutorials/category", dataObj);
result.success(function(data, status, headers, config) {
alert("success");
$scope.message = data;
});
result.error(function(data, status, headers, config) {
alert("failure message: " + JSON.stringify({
data : data
}));
});
$scope.name = '';
}
}
]);
And my html is
<body ng-app="categoryApp">
<section class="panel" ng-controller="submitCategory">
<header class="panel-heading"> Basic Forms </header>
<div class="panel-body">
<form role="form" method="post" ng-submit="submitClick()">
<div class="form-group">
<label for="category">Category</label> <input type="text"
class="form-control" id="exampleInputEmail1" name="name"
placeholder="Category" ng-model="name">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</section>
</body>
And my controller method is
#RequestMapping(value = "/category", method = RequestMethod.POST)
public ResponseEntity<String> postCategory(#RequestBody Category category,
Model model) {
categoryService.save(category);
return new ResponseEntity<String>("success", HttpStatus.OK);
}
The issue is caused by ResponseEntity<String> .Your code java should be like this:
#RequestMapping(value = "/category", method = RequestMethod.POST)
public ResponseEntity<String> postCategory(#RequestBody Category category,
Model model) {
categoryService.save(category);
return new ResponseEntity<String>("success", HttpStatus.OK); }
So I have a form inside an ng-dialog plugin for angular js. The contents of the ng-dialog is loaded from external html file. The problem is that when I try to save the data it is undefined. I suspect that I am missing updating the ng-model that I use, but it is not clear how to do it. I have looked to some similar examples, but it still does not work.I want to collect the data when the button inside the form is pressed, not when the dialog is closed, but when closed will do as well. Here is my code:
angular.app.js
myApp.controller('RequestController', function ($scope, $http, $location, $window, subtitleRequestService, $sce, subtitlesApiServiceUrl, helperService, ngDialog) {
$scope.string_identifier = helperService.getParameterByName("v");
$scope.availableSubtitles = null;
$scope.request = {
status: "pending",
status_reason: "",
status_reason_f: ""
};
var getAvailableSubtitles = function()
{
subtitleRequestService.getAvailableSubtitlesForRequest().then(
function (res) {
var subs = res.data.message;
$scope.availableSubtitles = subs;
},
function () {
alert('Error');
}
);
};
$scope.saveStatus = function()
{
var sts = ($scope.request.status_option === "accepted" ? $scope.request.status_reason : $scope.request.status_reason_f);
$http.post(subtitlesApiServiceUrl + "changeRequestStatus/request_id/" + $scope.string_identifier + "/status/" + $scope.request.status + "/status_reason/" + sts)
.success(function (data, status, headers, config) {
alert(data.message);
}).error(function (data, status, headers, config) {
alert(data);
});
};
$scope.changeStatus = function()
{
getAvailableSubtitles();
var dialogInstance = ngDialog.open({
//appendTo: window.parent.document.getElementsByTagName('body'),
template: "/templates/change-request-status.html",
scope: $scope,
controller: 'RequestController',
className: 'ngdialog-theme-default'
});
};
});
externalTeamplate.html
<div class="ngdialog-message" ng-controller="RequestController">
<h3>Schimbă status</h3>
<div class="form">
<form class="form" name="$scope.request">
<div class="row">
<label for="status_options">Status</label>
<select name="status_options" id="status_options" ng-model="request.status_option">
<option value="pending" selected="selected">În procesare</option>
<option value="accepted">accepted</option>
<option value="rejected">rejected</option>
<option value="deleted">deleted</option>
<option value="in_translation">in_translation</select>
</select>
</div>
<div class="row" ng-show="request.status_option !== 'accepted'">
<label for="status_reason">Reason:</label>
<input type="text" id="status_reason" size="35" maxlength="144" ng-model="request.status_reason" />
</div>
<div class="row" ng-show="request.status_option=='accepted'">
<label for="status_reason_f">Please select:</label>
<select id="status_reason_f" ng-repeat="(key, value) in availableSubtitles" ng-model="request.status_reason_f">
<option value="{{key}}">{{value}}</option>
</select>
</div>
</form>
</div>
</div>
<div class="ngdialog-buttons">
<button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="saveStatus()">Salvează</button>
</div>
What am I missing? Thanks!
I just wanna post some changes to the database. This is my angular - the problem is, it dosn't take values from my html inputs.
See section 2 of code:
mainController = function ($scope, $http) {
$scope.post = {};
console.log($scope);
console.log($scope.post);
$http.get('/api/todos')
.success(function(data) {
$scope.posts = data.posts;
$scope.datas = data;
// console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.editTodo = function() {
console.log($scope.post);
$http.post('/post/edit', $scope.post)
.success(function(data) {
$scope.post = {};
console.log($scope.post);
$scope.posts = data.posts;
$scope.datas = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}
Section 2:
<div class="comment" ng-repeat="post in posts | filter:search:strict | orderBy:predicate:reverse">
<div class="comment-content">
<form>
<input type="text" class="" ng-model="post.id" />
<input type="text" class="h2" ng-model="post.title" />
<textarea ng-model="post.content" ></textarea>
<span class="submitcontent" ng-click="editTodo()">
Submit
</span>
</form>
</div>
</div>
I don't get why my $scope.post obj is allways equal to: Object {} and my log from the node server shows:
{ id: undefined, postTitle: undefined, postContent: undefined }
POST /post/edit 200 8ms - 2.92kb
In your ng-repeat directive post is the current post NOT $scope.post. Just pass the post you're dealing with to your edit function:
<span class="submitcontent" ng-click="editTodo(post)">Submit</span>
JavaScript:
$scope.editTodo = function(p) {
console.log(p); // will have your id, title and content.
};
See solution below:
I'm trying to connect to a Parse.com Rest backend and display data from object values.
HTML (I put several angular calls to be sure to catch output):
<div ng-controller="MyController">
<p>{{item}}<p>
<p>{{items}}<p>
<p>{{item.firstName}}<p>
<p>{{data}}<p>
</div>
JAVASCRIPT rest:
function MyController($scope, $http) {
$scope.items = [];
$scope.getItems = function() {
$http({method : 'GET',url : 'https://api.parse.com/1/classes/Professional/id', headers: { 'X-Parse-Application-Id':'XXXX', 'X-Parse-REST-API-Key':'YYYY'}})
.success(function(data, status) {
$scope.items = data;
})
.error(function(data, status) {
alert("Error");
});
};
}
This won't work, it does strictly nothing, not even a message in the console.
I know the rest call got the correct credential, as I'm able to get object content returned when I test it with a rest tester program. Maybe the URL should not be absolute ?
Any clue is very welcome, i've spent DAYS on that.
SOLUTION:
Thanks to the help of people answering this thread, I was able to find the solution to this problem so I just wanted to contribute back:
Get Json object data from Parse.com backend, pass it authentification parameters:
function MyController($scope, $http) {
$scope.items = [];
$scope.getItems = function() {
$http({method : 'GET',url : 'https://api.parse.com/1/classes/Professional', headers: { 'X-Parse-Application-Id':'XXX', 'X-Parse-REST-API-Key':'YYY'}})
.success(function(data, status) {
$scope.items = data;
})
.error(function(data, status) {
alert("Error");
});
};
Notice that ' ' necessary arround header key object values. Those ' ' are not necessary around method and url keys.
Template that list all 'firstName' of each object:
<div ng-controller="MyController" ng-init="getItems()">
<ul>
<li ng-repeat="item in items.results"> {{item.firstName}} </li>
</ul>
</div>
Notice: "item in items.results". "results" is necessary because the return value is a JSON object that contains a results field with a JSON array that lists the objects. This could save you some headache.
Also notice "ng-init": if you don't put that, or any other form of call to the getItem(),then nothing will happen and you will be returned no error.
That was my first try of Angularjs, and i'm already in love ^^.
Based in your request the controller should be:
HTML
<div ng-controller="MyController">
<button type="button" ng-click="getItems()">Get Items</button>
<ul>
<li ng-repeat="item in items"> item.firstName </li>
</ul>
</div>
JS
function MyController($scope, $http) {
$scope.items = []
$scope.getItems = function() {
$http({method : 'GET',url : 'https://api.parse.com/1/classes/Users', headers: { 'X-Parse-Application-Id':'XXXXXXXXXXXXX', 'X-Parse-REST-API-Key':'YYYYYYYYYYYYY'}})
.success(function(data, status) {
$scope.items = data;
})
.error(function(data, status) {
alert("Error");
})
}
}
Just a little update to the newer versions of Angular (using .then since version 1.5):
myApp.controller('MyController', function($scope, $http) {
$scope.items = []
$http({
method: 'GET',
url: 'https://api.parse.com/1/classes/Users',
headers: {'X-Parse-Application-Id':'XXXXXXXXXXXXX', 'X-Parse-REST-API-Key':'YYYYYYYYYYYYY'}
})
.then(function successCallback(response) {
alert("Succesfully connected to the API");
$scope.items = data;
}, function errorCallback(response) {
alert("Error connecting to API");
});
});
var app = angular.module("app",[]);
app.controller("postcontroller", function($scope, $http){
$scope.getAllProjects = function() {
var url = 'https://reqres.in/api/products';
$http.get(url).then(
function(response) {
$scope.projects = response.data.data;
},
function error(response) {
$scope.postResultMessage = "Error with status: "
+ response.statusText;
});
}
$scope.getAllProjects();
});
<div ng-app="app">
<div ng-controller="postcontroller">
<div class="panel-body">
<div class="form-group">
<label class="control-label col-sm-2" for="project">Project:</label>
<div class="col-sm-5">
<select id="projectSelector" class="form-control">
<option id="id" ng-repeat="project in projects"
value="{{project.id}}">{{project.name}}</option>
</select>
</div>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>