Issue with populating partial view with AngularJs and MVC - javascript

I am new to AngularJs. I am using a partial view for Create and Edit operation but facing some issue wile retrieving the data.
The data is being retrieved successfully from my MVC controller but is unable to populate the view.
Here is the JS I am using
(function (angular) {
'use strict';
angular.module('Sub_Ledger_Category_Create_app', [])
.controller('Sub_Ledger_Category_Create_ctrl', function ($scope, $http, $location) {
$scope.SubLedgerCategoryModel = {};
GetRequestType();
function GetRequestType() {
$http.get('/Common/Get_Action_Request')
.success(function (result) {
//debugger;
// $scope.SubLedgerCategoryModel = data;
if (result == "Create") {
$("#txt_Master_Subledger_Category").html("<h3 class='box-title'> Create Sub Ledger Category </h3>");
// $("#txt_Master_Accounting_Group_Group_id").val(0);
}
else {
$("#txt_Master_Subledger_Category").html("<h3 class='box-title'> Edit Sub Ledger Category</h3>");
//GetEditData();
$scope.GetEditData();
}
$("#Master_Subledger_Category").val(result)
NProgress.done();
})
.error(function (data, status, headers, config) {
NProgress.done();
$("div.failure").text("Unable to retrieve Request Type");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
});
};
$scope.GetEditData = function () {
$http.get('/Master_Subledger_Category/GetEditData')
.success(function (data, status, headers, config) {
debugger;
$scope.SubLedgerCategoryModel = data;
console.log(data);
})
.error(function (data, status, headers, config) {
NProgress.done();
$("div.failure").text("Retrive Failure");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
});
};
$scope.InsertSubledgerCategory = function () {
NProgress.start();
var Request_Type = $("#Master_Subledger_Category").val();
var Url_Master_Subledger;
if (Request_Type == "Create") {
Url_Master_Subledger = "/Master_Subledger_Category/Create_Master_Subledger_Category_Ajax";
}
else {
Url_Master_Subledger = "/Master_Subledger_Category/Test";
}
$http({
method: 'POST',
url: Url_Master_Subledger,
data: $scope.SubLedgerCategoryModel
}).success(function (data, status, headers, config) {
if (data.success === true) {
NProgress.done();
$("div.success").text("Successfully Created");
$("div.success").fadeIn(300).delay(1500).fadeOut(800);
$scope.SubLedgerCategoryModel = {};
console.log(data);
}
else {
NProgress.done();
$("div.failure").text("Saveing Failure");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
}
}).error(function (data, status, headers, config) {
NProgress.done();
$("div.failure").text("Saveing Failure");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
console.log($scope.message);
});
};
})
.config(function ($locationProvider, $sceProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$sceProvider.enabled(false);
});
})(angular);
Here is the HTML:
<div class="form-horizontal" ng-app="Sub_Ledger_Category_Create_app">
<div class="box-body" ng-controller="Sub_Ledger_Category_Create_ctrl">
<div class="form-group">
<label for="txt_Master_Subledger_Category_Name" class="col-sm-2 control-label">Sub Ledger Category</label>
<div class="col-sm-10">
<input class="form-control" ng-model="SubLedgerCategoryModel.Sub_Ledger_Cat_Name" id="txt_Master_Subledger_Category_Name" name="txt_Master_Subledger_Category_Name" autofocus placeholder="Sub Ledger Category">
<input ng-model="SubLedgerCategoryModel.Sub_Ledger_Cat_ID" name="txt_Master_Subledger_Category_ID" id="txt_Master_Subledger_Category_ID" hidden />
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" value="Save" ng-click="InsertSubledgerCategory()" class="btn btn-info pull-right">Save</button>
<div class="text-red alert-box failure pull-right margin-r-5"></div>
<div class="text-green alert-box success pull-right margin-r-5"></div>
</div>
<!-- /.box-footer -->
</div>
</div>
Unfortunately I am unable to populate the view but in Console log I am able to view the data, helpful if anybody and help me.

AngularJs prevents loading HTML in this way by default. You might be getting an error on browser console: attempting to use an unsafe value in a safe context.
This is due to Angular's Strict Contextual Escaping (SCE) mode (enabled by default). Have a look to this for more information.
To resolve this issue you have 2 solutions:
$sce
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar);
ngSanitize: include the angular-sanitize.min.js resource and add the dependency in module.
hope this will help.

I have only changed the following
scope.SubLedgerCategoryModel = data;
to
scope.SubLedgerCategoryModel = data[0]:
and its resolved my issue.

Related

Live refresh when new data is inserted angularjs

I want to get a live update of records when a new record is inserted into the db. when a new record is inserted i want the div containing the item in cart to refreshed
.controller('newitem_ctrl', ['$scope', '$http', function($scope, $http) {
$http.get('http://localhost/spree/work/items/item.php').success(function(data) {
$scope.cart = data;
});
$scope.newitem = function() {
$ionicLoading.show({
template: '<p>Wait...</p><ion-spinner></ion-spinner>'
});
event.preventDefault();
$http.post("http://localhost/work/scripts/new_payment.php", {
'item': $scope.item
})
.success(function(data, status, headers, config) {
console.log(data)
}).error(function(error) {
console.error(error);
});
};
}]);
HTML
<div ng-controller="newitem_ctrl">
<form method="post">
<input type="text" name="item_name" placeholder="Item Name" ng-model="item" />
<button class="button button-balanced" ng-click="newitem()">Add</button>
</form>
<div ng-repeat="item in cart">
{{item.product_name}}
</div>
</div>
Try this
$http({
method: 'POST',
url: 'http://localhost/work/scripts/new_payment.php',
data: { 'item': $scope.item }
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.cart.push($scope.item);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Unrelated: .success and .error callbacks are obsolete. Use .then
You can do something like this.
Add the item in the cart array when you get a success response from post call.
.controller('newitem_ctrl', ['$scope', '$http', function ($scope, $http) {
$http.get('http://localhost/spree/work/items/item.php').success(function(data){
$scope.cart=data;
});
$scope.newitem=function() {
$ionicLoading.show({template: '<p>Wait...</p><ion-spinner></ion-spinner>'});
event.preventDefault();
$scope.newItem = {'item':$scope.item}
$http.post("http://localhost/work/scripts/new_payment.php",
$scope.newItem)
.success(function(data,status,headers,config){
console.log(data);
$scope.model = {product_name: $scope.newItem};
$scope.cart.push($scope.model);
}).error(function(error){
console.error(error);
});
}
}])
It will update the div because the bound array is changed
Because You're not using socket.io or something alike
And You're asking about:
update of records when a new record is inserted into the db
I can only decide to continuously request the php script and get fresh data.
I've made additions to Your code.
So You can copy-paste it:
.controller('newitem_ctrl', ['$scope', '$http', function ($scope, $http) {
function getCart(currentScope) {
$http
.get('http://localhost/spree/work/items/item.php')
.then(function(data) { // success
currentScope.cart = data;
})
.catch(function(err) { // error
console.log(err);
})
.finally(function() { // always
// to not throttle browser and server with requests will wait for http request end
// and recall getCart again
setTimeout(function() {
getCart(currentScope);
}, 5000); // 5 sec
});
}
getCart($scope);
$scope.newitem = function() {
$ionicLoading
.show({template: '<p>Wait...</p><ion-spinner></ion-spinner>'});
event.preventDefault();
$http
.post("http://localhost/work/scripts/new_payment.php", {'item': $scope.item})
.then(function(data, status, headers, config) { // success
console.log(data);
})
.catch(function(error) { // error
console.error(error);
})
.finally(function() { // always
getCart($scope);
$ionicLoading.hide();
});
};
}]);

AngularJS - Some dynamic contents loads very late

I have an Angular JS application in which some dynamic rows of data are loaded through a rest API. This section of html data are loaded very late after the whole page is loaded and hence looks bad.
HTML
<div class="row">
<div class="form-group" ng-repeat="rows1 in entity.pageSection1Rows">
<!-- Around five html columns -->
<!-- The CONTENTS here loads very late after the whole page is loaded -->
</div>
</div>
<div class="row">
<div class="form-group" ng-repeat="rows2 in entity.pageSection2Rows">
<!-- Around five html columns -->
<!-- The CONTENTS here loads very late after the whole page is loaded -->
</div>
</div>
Javascript
myApp.controller('createController', function($scope, $http, $location) {
$scope.entity = {};
$http.get("/restapi/serviceA")
.success(function(data, status, headers, config) {
$scope.entity.pageSection1Rows = data;
});
$http.get("/restapi/serviceB")
.success(function(data, status, headers, config) {
$scope.entity.pageSection2Rows = data;
});
// Rest APIs to load data for drop downs
$http.get("/restapi/dropdown1")
.success(function(data, status, headers, config) {
$scope.dropdown1 = data;
});
$http.get("/restapi/dropdown2")
.success(function(data, status, headers, config) {
$scope.dropdown2 = data;
});
$http.get("/restapi/dropdown3")
.success(function(data, status, headers, config) {
$scope.dropdown3 = data;
});
$http.get("/restapi/dropdown4")
.success(function(data, status, headers, config) {
$scope.dropdown4 = data;
});
$scope.add = function() {
$http.post("/restapi/entity", $scope.entity).success(function(data, status, headers, config, statusText) {
$location.path('/home');
}).error(function(data, status, headers, config, statusText) {
console.log("Error : " +statusText);
});
}
})

Issue with angular animation and undefined javascript values

I am trying to get an angular animation to be triggered upon an unsuccessful login (either when the server sends a 4xx (e.g. 403) or when no credentials are provided).
Here is the controller:
.controller('SigninCtrl', ['$scope', '$rootScope', '$cookies', '$state', '$animate', 'signinService', function ($scope, $rootScope, $cookies, $state, $animate, signinService) {
$scope.signin = function () {
$scope.shake = false;
if ($scope.credentials) {
signinService.signin($scope.credentials, function (status, memberRole) {
$scope.shake = false;
//TODO: necessary to check status?
if (status === 200) {
...
}
},
function () {
$scope.shake = true;
});
}
else {
//TODO: only shakes/works once!
$scope.shake = true;
}
}
}]);
The form:
<form class="form-signin" ng-class="{shake: shake}" name="signinForm" ng-submit="signin()" novalidate>
<h2 class="form-signin-heading signin-title">{{'SIGNIN' | translate}}</h2>
<input type="email" ng-required name="username" ng-model="credentials.username" class="form-control" placeholder="{{'SIGNIN_FORM_EMAIL'| translate}}"/>
<input type="password" ng-required name="password" ng-model="credentials.password" class="form-control" placeholder="{{'SIGNIN_FORM_PASSWORD'| translate}}"/>
<button class="btn btn-lg btn-primary btn-block" type="submit">{{'SIGNIN' | translate}}</button>
<div class="forgot-password">
<a ui-sref="sendpasswordresetinformation">{{'SIGNIN_FORM_FORGOTTEN_PASSWORD' | translate}}</a>
</div>
</form>
However, if the form has no credentials in the inputs (nothing as in not even the empty string) the form shakes only once.
Can someone please help?
edit 1:
.factory('signinService', ['$http', function ($http) {
return {
signin: function (credentials, successCallback, errorCallback) {
var transform = function (data) {
return $.param(data);
}
return $http.post('/api/signin', credentials, {
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: transform
}).success(function (data, status, headers) {
if (status === 200) {
successCallback(status, headers('MEMBER_ROLE'));
}
else {
console.log('auth error');
successCallback('error');
}
}).error(function(data, status, headers) {
console.log("error!", data, status, headers);
errorCallback();
});
}
}
}]);
Changing the controller to :
...
$scope.signin = function () {
$scope.shake = false;
$scope.$apply();//ADDED!
...
fixed the issue. Thanks floribon...

Pass ng-data to scope

I'm trying to create a live search function with AngularJS. I got a input field:
<input type="text" placeholder="Search" data-ng-model="title" class="search">
it there away to pass the search keyword inside the scope so i can perform a live search (JS) and display the results directly to the DOM
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('http://api.org/search?query=<need to pass search name here>&api_key=').
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
});
Inside the angular controller use a watch expression.
$scope.$watch('title', function (newValue, oldValue) {
if(newValue != oldValue) {
$http.get('http://api.org/search?query=' + newValue + '&api_key=')
.success(function(data, status, headers, config) { /* Your Code */ })
.error(function(data, status, headers, config) { /* Your Code */ });
}
});
You can use watch as #Justin John proposed, or can use ng-change
when using ng-change your controller should look something like this
app.controller("Controller", function($scope, $http) {
$http.defaults.headers.common["Accept"] = "application/json"; //should be moved to run block of your app
$scope.details = [];
$scope.search= function() {
$http.get("http://api.org/search?query="+$scope.title+"&api_key=")
.success(function(data, status, headers, config) { .... })
.error(function(data, status, headers, config) {//handle errors });
}
});
and your html
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$scope.search= function() {
var url = "http://api.org/search?query="+$scope.title+"&api_key=";
$http.defaults.headers.common["Accept"] = "application/json";
$http.get(url).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
};
});

Angular $http.post not reaching the server

I'm having a problem getting $http.post to fire:
app.controller('editPageController', function($scope, $routeParams, $http) {
$scope.page = $routeParams.pageid;
// get page data from server
$http.get('/pages/' + $scope.page).
success(function(data, status, headers, config) {
$scope.Name = data[0].name;
$scope.Content = data[0].content;
$scope.Location = data[0].location;
}).
error(function(data, status, headers, config) {
alert("Can't get the page from the server");
});
// save page data on the server
$scope.saveEditPage = function() {
var postOBject = {Name: $scope.Name, Content: $scope.Content, Location: $scope.Location};
$http.post('/pages/' + $scope.page + '/edit', postObject).
success(function(data, status, headers, config) {
alert("success");
}).
error(function(data, status, headers, config) {
alert("Can't edit the page on the server");
});
};
});
The template code:
<script type="text/ng-template" id="editPage.html">
<h1>Edit page:</h1>
<form ng-submit="saveEditPage()">
<p>Name:</p>
<input type="text" ng-model="Name" value="{{Name}}">
<p>Content:</p>
<textarea ng-model="Content">{{Content}}</textarea>
<p>Location:</p>
<input type="text" ng-model="Location" value="{{Location}}">
<p><input type="submit" value="Save"> <input type="button" value="Cancel" ng-click="$back()"></p>
</form>
Unfortunately the $http.post does not fire. I tried wrapping the post call around $scope.$apply and it didn't work either.
How can I fix this?
Thanks
EDIT: FIXED
JavaScript variable names are case sensitive. You have declared postOBject but you are passing postObject.
ReferenceError: postObject is not defined
If I correct the typo, it's working as expected for me.
BTW I recommend using IDE with static analysis - it will inform you about undefined variables immediately. Also Firebug or Chrome DevTools javascript console are almost absolutely necessary for javascript development.

Categories

Resources