Unable to append rendered text in angular JS - javascript

My controller:
myApp.controller('actionEditController', ['$scope', '$stateParams', '$sce',function ($scope, $stateParams, $sce) {
$context = $scope;
$.get(apiHost + "/action/entity/" + $stateParams.id)
.success(function (response) {
angular.module('broConsoleApp', ['ngSanitize']);
var action = response['RESPONSE'];
action.params = JSON.parse(action.paramsJson);
console.log(action);
var table = $.hbs("/templates/action.hbs", action);
var el=angular.element(table);
$scope.content= $sce.trustAsHtml(table);
console.log(table);
})
.error(function (jqXHR, textStatus, errorThrown) {
console.error("Error retrieving action", textStatus, errorThrown);
});
}])
;
My .hbs :
<div>
<input name="name" type="text" value="{{name}}"/>
<input name="id" type="text" readonly="readonly" value="{{id}}"/>
<input name="type" type="text" readonly="readonly" value="{{actionType}}"/>
</div>
My .html file :
<div ng-app="myApp" ng-controller="actionEditController" >
<h2 class="marcellus text-center"> EDIT ACTION </h2>
<div ng-bind-html="content">
</div>
</div>
I am getting the rendered data in table from
$.hbs
.However the ng-bind-html does not seem to be appending / binding this value to the HTML . The final output is only
EDIT ACTION
The rendered data does not display.

Related

Sending form with optional parameters POST-method + angularJS

I'm trying to make a form that sends an url of the type /:id/:option where I know the id before entering the form but the option-attribute is the one that the user selects from the radio-buttons. After submitting the form I should move to the page /:id/:option. I'm also using angulasJS with my application.
So how can I send the url with the POST-method?
html
<form method="POST">
<div class="voteOptions" ng-repeat="item in id.data.options">
<label class="radioButtons">{{item.title}} votes:{{item.votes}}
<input type="radio" name="option" value={{item.option}}>
<span class="radioSelector"></span>
</label>
</div>
<input type="submit" id="voteSubmit" value="Vote!">
</form>
.post-call
app.post('/:id/:option', (req, res) => {
var poll = polls[req.params.id-1];
poll.options[req.params.option-1].votes++;
res.json(poll);
});
Create Controller and make Http call from there.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form method="POST" ng-submit="submit()">
<div class="voteOptions" ng-repeat="item in options">
<label class="radioButtons">{{item.title}} votes:{{item.votes}}
<input type="radio" name="option" value={{item.option}} ng-model="option.val">
<span class="radioSelector"></span>
</label>
</div>
<input type="submit" id="voteSubmit" value="Vote!">
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
var id = 12345;
$scope.option = {val:0};
$scope.options= [{
title : 'option-1',
votes : 5,
option : 1
},{
title : 'option-2',
votes : 5,
option : 2
}];
$scope.submit = function(){
console.log('Url', `<domain>/${id}/${$scope.option.val}`);
// Generate url and call http post
// $http.post(url, body, config)
// .success(function (data, status, headers, config) {
// })
// .error(function (data, status, header, config) {
// });
}
});
</script>
</body>
</html>

send the id from the table to the controller with angularjs

I wonder how can I send the id of the selected row from my table to the controller when I try to show the details of these row,this is my code:
app.js:
.controller("etudmodifCtrl", ["$scope", "$http", "filterFilter", "$rootScope", "logger", "$filter", "$modal", "$log", function ($scope, $http, filterFilter, $rootScope, logger, $filter, $modal, $log) {
$http({
method: 'GET',
url: 'http://localhost:50001/api/Students/' + $scope.store.id
}).success(function (data) {
$scope.firstname = data.FirstName;
$scope.lastname = data.LastName;
$scope.email = data.Email;
console.log("success");
}).error(function (data, status, headers, config) {
console.log("data error ...");
});
$scope.open = function () {
var modalInstance;
modalInstance = $modal.open({
templateUrl: "myModalContent1.html",
controller: "ModalInstanceCtrl",
resolve: {
items: function () {
return $scope.items
}
}
}), modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem
}, function () {
$log.info("Modal dismissed at: " + new Date)
})
}
}])
my html code:
<table class="table table-responsive table-hover" ng-controller="etudmodifCtrl">
<tr ng-repeat="store in currentPageStores">
<td align="center">{{store.LastName}}</td>
<td align="center">{{store.FirstName}}</td>
<td align="center">{{store.Email}}</td>
<td align="center">{{store.Class}}</td>
<td align="center">
<script type="text/ng-template" id="myModalContent.html">
< div class ="modal-header">Modify Informations</div><div class = "modal-body modal-dialog modal-lg3" data-ng-controller = "etudmodifCtrl">
<div class="panel-body" >
<div class="col-md-6">
<div class="form-group">
<label for="" class="col-sm-2">FirstName</label>< div class = "col-sm-10"><input type = "email" class ="form-control" ng-model = "firstname">
</div>
</div >< /div>
<div class="form-group">
<label for="" class="col-sm-2">LastName</label>< div class = "col-sm-10"><input type = "email" class ="form-control" ng-model = "lastname">
</div>
</div >< /div>
<div class="form-group">
<label for="" class="col-sm-2">Email</label>< div class = "col-sm-10"><input type = "email" class ="form-control" ng-model = "email">
</div>
</div >< /div>
</script>
</td>
</tr>
</table>
<button type="button" onclick="window.location = '" aria-label="Center Align" ng-click="open()" data-toggle="modal" data-target=".bs-example-modal-lg">Modify</button>
I try to send the id via the open function but I get a syntax error
thanks for help
In button bg-click pass the id by using ng-click="open(store.storeId)" complete code
<button type="button"
aria-label="Center Align"
ng-click="open(store.storeId)"
data-toggle="modal"
data-target=".bs-example-modal-lg">Modify</button>
And change your open function to accept a parameter like this
$scope.open = function (id) {
............
............
}
for more detail, who to pass value from controller to model controller see this Pass parameter to modal

How to load data in ngDialog

I have a requirement where I need to open a dialog from a jsp page and while opening the dialog, I need to load it with some prepopulated data from the server (using an AJAX call). If I make the AJAX call before opening the dialog, I get the data but the dialog loads like a new page. If I try to get the data in the new controller, the dialog still does not reflect the data. What should I use to make sure the dialog reflects the data that I am getting from the server
<div class="container-fluid" ng-controller="EditUserController">
<div class="text-center container-fluid">
<label class="sub-header">Edit User: {{userEmail}}</label>
</div>
<form action="editUser" method="post" name="editForm">
<div>
<div class="pull-right">
<label>Delete User</label><br> <a href="#"
class="btn btn-block btn-sm btn-danger" ng-click="deleteUser(userEmail)">{{userEmail}}</a>
</div>
<div>
<label>Change Role</label>
</div>
<div>
<label>
<input type="checkbox" ng-model="superVisor" name="superVisorFlag"
ng-true-value="1" ng-false-value="0" value="${existingUser.superVisorFlag}">
Make a Supervisor</label>
</div>
<div>
<input type="text" class="form-control" ng-model="email"
name="emailAddress" ng-disabled = "true"
ng-options="email for email in userEmail"
value="${existingUser.emailAddress}"
placeholder="Enter New User Email Address" bs-typeahead>
</div>
<div>
<input type="text" class="form-control" ng-model="firstName"
name="firstName" value="${existingUser.firstName}"
placeholder="Enter First Name" bs-typeahead>
</div>
<div>
<input type="text" class="form-control" ng-model="lastName"
name="lastName" value="${existingUser.lastName}"
placeholder="Enter Last Name" bs-typeahead>
</div>
<div>
Save Changes
</div>
</div>
</form>
</div>
<script type="text/javascript"
src="<c:url value="/resources/scripts/admin.js"/>"></script>
The above is a jsp for the dialog. Below is my js file -
var app = angular.module('scc-admin', [ 'ngDialog', 'mgcrea.ngStrap' ]);
app.factory("UserList", function() {
var UserList = {};
UserList.data = [ {
userId : 111,
userFirstName : "xxx",
userLastName : "yyy",
userEmail : "xxx.yyy#zzz.com",
userRole : "Admin"
}, {
userId : 222,
userFirstName : "second",
userLastName : "last",
userEmail : "second.last#zzz.com",
userRole : "Manager"
}];
return UserList;
});
app.controller('UserSettingsController', function($scope, ngDialog, UserList,$http) {
// variable for the bashboard list
$scope.userList = UserList;
$scope.editUser = function(userEmail) {
$scope.userEmail = userEmail;
ngDialog.open({
template : 'editUser' ,
className : 'ngdialog-theme-default',
controller : 'EditUserController',
closeByEscape : true,
scope : $scope
});
};
$scope.addUser = function() {
ngDialog.open({
template : 'addUser',
className : 'ngdialog-theme-default',
controller : 'AddUserController',
closeByEscape : true,
scope : $scope
});
};
});
app.controller('EditUserController', function($scope, ngDialog, $http) {
ngDialog.template = $scope.output;
ngDialog.$modelValue = $scope.output;
var responsePromise = $http.get("initUser?email=" + $scope.userEmail);
responsePromise.success(function(data, status, headers, config) {
$scope.output = data;
console.log(data);
});
console.log($scope);
$scope.deleteUser = function(){
$scope.cfdump = "";
var str = {emailAddress : $scope.userForm.emailAddress.$modelValue};
str = JSON.stringify(str);
var request = $http({
method: 'post',
url: "deleteUser?formData=" + str,
data: ({formData:str})
});
request.success(function(html){
alert("success");
});
request.error(function(errmsg){
alert("Unable to delete user");
});
}
});
I am opening a dialog in usersettings controller and trying to load it with default data. I tried setting the new dialog's template to the output of the AJAX call, it did not work. What am I missing here?
After consulting the documentation, I learned following solution. It should work for you like it did for me.
To pass data (JSON Object) for ng-model inside the ngDialog, you can declare your ngDialog as following.
ngDialog.open({
template: 'my-template.html',
className: 'ngdialog-theme-plain',
data: $scope.myJSONObject
});
Now, with the above part done, you need to bind the data in your popup ngDialog, so go and put ngDialogData.myJSONObjectFieldName in your ng-model.
Consider following example for further elaboration. We assume that we have myJSONObject as following.
myJSONObject={
first_name: 'John',
last_name: 'Doe'
};
To use first_name inside your ngDialog's ng-model, simply put ng-model="ngDialogData.first_name".
To check whether the controller(VM) data is received in Modal Dialog use this
<pre>{{vm|json}}</pre>
Module and Controller:
var app = angular.module("DemoApp",['ngDialog']);
app.controller("DemoController",["$rootScope","ngDialog","productService",function($rootScope,ngDialog,productService){
var vm=this;
$rootScope.ngDialog = ngDialog; // to close Dialog using "ngDialog.close();" in ProductDialog.html
/* vm.products=[{brand:"Apple", price:60000, os:"iOS"},
{brand:"Samsung", price:35000, os:"Android"},
{brand:"Microsoft Lumia", price:30000, os:"Windows 10"}
];
*/
vm.getProductDetails=function() {
productService.getData().then(function (response) {
if (response.data) {
vm.products=response.data;
vm.ProdDialog();
}
});
};
vm.productPopup = function(x){
ngDialog.open({
template: 'ProductDialog.html',
className:'ProductDetailsDialog'
scope:$scope,
data:x,
closeByDocument:true
});
}
vm.getProductDetails();
}]);
Service:
app.factory("productService",["$http",function($http){
return {
getData: function() {
return $http.get("http://xxxxxxx/xxx/xxxxx");
}
};
}]);
DemoController.html
/* <table>
<tr>
<th>Brand</th>
<th>Price</th>
<th>OPerating System</th>
<th>Open ngDialog</th>
</tr>
<tr ng-repeat="x in vm.products">
<td ng-bind="x.brand"></td>
<td ng-bind="x.price| currency:"₹":2"></td>
<td ng-bind="x.os"></td>
<td><button ng-click="vm.productPopup(x)"></button></td>
</tr>
</table>
*/
ProductDialog.html:
<div class="ProductDetailsDialog">
<div class="ngdialog-content" role="document">
<div class="modal-header">
<button type="button" class="close" ng-click="ngDialog.close();">×</button>
<h4 class="modal-title">Product Detials</h4>
</div>
// <pre>{{vm|json}}</pre> //
<div class="modal-body">
<h4>Brand:<span ng-bind="ngDialogData.brand"></span></h4>
<h4>Price:<span ng-bind="ngDialogData.price | currency:"₹":2"></span></h4>
<p>Operating System:<span ng-bind="ngDialogData.os"></span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default">OK</button>
</div>
</div>
</div>

How do I send form data to server using angular?

Currently, I am using a server side framework CakePHP to build my app.
I need to integrate angular into my app.
Currently, I send the following inputs
User.old_password, User.new_password, User.new_password_confirm
to this url /mypasswords/new using POST
This works just fine.
I understand that to send data to server side I need to use services in Angular.
This is my Angular code so far.
var app = angular.module("myApp", []);
app.controller('passwordController', ['$scope', function($scope) {
$scope.submitted = false;
$scope.changePasswordForm = function() {
if ($scope.change_password_form.$valid) {
// Submit as normal
} else {
$scope.change_password_form.submitted = true;
}
}
}]);
services = angular.module('myApp.services', ['ngResource']);
services.factory("UserService", function($http, $q) {
var service;
// service code here
});
So what do I write in the //service code here part? What other parts am I missing?
My form currently looks like this as html after being rendered. (I know I probably have to remove action and method attributes from my form. Do I?)
<form action="/mypasswords/new" id="change_password_form" name="change_password_form" ng-controller="passwordController" ng-submit="changePasswordForm()" method="post" accept-charset="utf-8" class="ng-scope ng-pristine ng-valid">
<div style="display:none;"><input type="hidden" name="_method" value="POST"></div>
<input name="data[User][old_password]" id="u56" placeholder="Enter old password..." class="u56 profile_input" type="password">
<input name="data[User][new_password]" id="u57" placeholder="Enter new password..." class="u57 profile_input" type="password">
<input name="data[User][new_password_confirm]" id="u58" placeholder="Enter new password..." class="u58 profile_input" type="password">
<div id="u25" class="u25_container">
<div id="u25_img" class="clear_all_button detectCanvas" onclick="document.getElementById('change_password_form').reset()">
</div>
</div>
<div id="u27" class="u27_container">
<input id="u27_img" class="submit_button detectCanvas" type="submit" value="SAVE">
</div>
</form>
Thank you.
if you want just to send the form with ajax, No need to create factory, just do it in controller like this:
var app = angular.module("myApp", [$http]);
app.controller('passwordController', ['$scope', function($scope) {
$scope.submitted = false;
$scope.changePasswordForm = function() {
if ($scope.change_password_form.$valid) {
//note: use full url, not partial....
$http.post('http://myweb.com/mypasswords/new', change_password_form.Data)
.success(function(data, status, headers, config) {
//do anything when it success..
})
.error(function(data, status, headers, config){
//do anything when errors...
});
} else {
$scope.change_password_form.submitted = true;
}
}
}]);
And your form will looks like this:
<form id="change_password_form" name="change_password_form" ng-controller="passwordController" ng-submit="changePasswordForm()" method="post" accept-charset="utf-8" class="ng-scope ng-pristine ng-valid">
<div style="display:none;"><input type="hidden" name="_method" value="POST"></div>
<input name="data[User][old_password]" ng-model="Data.old_password" id="u56" placeholder="Enter old password..." class="u56 profile_input" type="password">
<input name="data[User][new_password]" ng-model="Data.new_password" id="u57" placeholder="Enter new password..." class="u57 profile_input" type="password">
<input name="data[User][new_password_confirm]" ng-model="Data.new_password_confirm" id="u58" placeholder="Enter new password..." class="u58 profile_input" type="password">
<div id="u25" class="u25_container">
<div id="u25_img" class="clear_all_button detectCanvas" onclick="document.getElementById('change_password_form').reset()">
</div>
</div>
<div id="u27" class="u27_container">
<input id="u27_img" class="submit_button detectCanvas" type="submit" value="SAVE">
</div>
</form>
Step 1: write form using normal html instead of FormHelper in CakePHP
The form should look like this:
<form name="change_password_form" ng-controller="passwordController"
ng-submit="changePasswordForm()">
<input name="data[User][old_password]" ng-model="data.User.old_password" type="password" placeholder="Enter old password..." class="u56 profile_input">
<input name="data[User][new_password]" ng-model="data.User.new_password" type="password" placeholder="Enter new password..." class="u57 profile_input">
<input name="data[User][new_password_confirm]" ng-model="data.User.new_password_confirm" type="password" placeholder="Enter new password again..." class="u58 profile_input">
<div id="u25"
class="u25_container">
<div id="u25_img"
class="clear_all_button detectCanvas" onclick="document.getElementById('change_password_form').reset()">
</div>
</div>
<div id="u27"
class="u27_container">
<button type="submit" id="u27_img" ng-click="debug()"
class="submit_button detectCanvas" />
</div>
</form>
Step 2: write the app.js in the following manner.
the X-Requested-With header is important if you want to use the CakePHP $this->request->is('ajax')
angular.module("myApp", [])
.controller('passwordController', function($scope, $http) {
$scope.changePasswordForm = function() {
console.log('change passwrd form activated');
//note: use full url, not partial....
$http({
method : 'POST',
url : '/mypasswords/new',
data : $.param($scope.data), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With' : 'XMLHttpRequest'
} // set the headers so angular passing info as form data (not request payload)
})
.success(function(data, status, headers, config) {
//do anything when it success..
console.log('works!');
})
.error(function(data, status, headers, config){
//do anything when errors...
console.log('errors!');
});
}
$scope.debug = function () {
console.log($scope);
}
});

Update textfield value with ajax data using angular js

I am using angular js directives for bootstrap. What i am trying for is to create an edit form on bootstrap modal when user clicks on edit button from list of items. Here is my code:
HTML:
<div class="modal-header">
<h3>Edit Template</h3>
</div>
<div class="modal-body">
<form name="form" class="form-horizontal" novalidate>
<fieldset>
<div class="span4" ng-class="smClass" ng-show="etemplate.status">{{etemplate.status}}</div>
<div class="control-group">
<label class="control-label" for="etemplateName">Name</label>
<div class="controls">
<input class="input-xlarge" id="etemplateName" ng-model="eTemplate.name" maxlength="150" type="text" required />
</div>
</div>
<div class="control-group">
<label class="control-label" for="etemplateDesc">Description</label>
<div class="controls">
<textarea id="templateDesc" id="etemplateDesc" ng-model="eTemplate.desc"></textarea>
</div>
</div>
<div class="center">
<input type="text" style="display:none;" ng-model="eTemplate.id" value="{{eTemplate.id}}" required />
<button type="button" ng-click="update(eTemplate)" class="btn btn-primary" ng-disabled="form.$invalid || isUnchanged(eTemplate)">Submit</button>
<button class="btn" ng-click="cancel()">Cancel</button>
</div>
</fieldset>
</form>
</div>
Controller:
controller('TemplateController', ['$scope', '$http', '$modal', function($scope, $http, $modal) {
var tmpId = '';
$scope.openEdit = function(id) {
tmpId = id;
var editTmpModalInstance = $modal.open({
templateUrl: 'editTemplateContent.html',
controller: 'ETModalInstance'
});
$http({
method: 'GET',
url: adminBaseUrl+'/get_template/',
params: {'id': tmpId}
}).
success(function(data, status, headers, config) {
$scope.$broadcast('EditTemplateDataReached', data);
}).
error(function(data, status, headers, config) {
});
}
}]).
controller('ETModalInstance', ['$scope', '$http', '$modalInstance', function($scope, $http, $modalInstance) {
$scope.emaster = {};
$scope.smClass = '';
$scope.eTemplate = {};
$scope.$on('EditTemplateDataReached', function(data) {
$scope.eTemplate = data;
$scope.$apply();
});
$scope.isUnchanged = function(eTemplate) {
return angular.equals(eTemplate, $scope.master);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
$scope.update = function(eTemplate) {
var strng = $.param(eTemplate);
};
}]).
My work around for achieving this is when user clicks on edit button id of selected item is passed in my controller which sends an ajax request to server and then fill the fields with respective values. However my fields are not populated when ajax data is returned.
Found the problem in my code i was using $scope for broadcasting and catching the data whereas i have to use $rootScope.
Wrong:
$scope.$broadcast('EditTemplateDataReached', data);
$scope.$on('EditTemplateDataReached', function(data) {
$scope.eTemplate = data;
$scope.$apply();
});
Correct:
$rootScope.$broadcast('EditTemplateDataReached', data);
$rootScope.$on('EditTemplateDataReached', function(e, data) {
$scope.eTemplate = data;
$scope.$apply();
});

Categories

Resources