I built a sample MVC application in which I tried to implement functionality to insert a record using angular js.
Here is the index cshtml page.
#{
ViewBag.Title = "Add User";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section adduser
{
#*Index.html*#
<div class="container-fluid" ng-app='MyData' ng-controller='DataController'>
<table class="table table-striped table-bordered table-responsive">
<tr>
<td>
<label class="text-primary">User Name:</label>
</td>
<td>
<input type="text" id="txtUserName" class="text-primary" required="required" ng-model="newUser" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" id="btnSubmit" class="btn btn-success" ng-click="AddUser()" />
</td>
</tr>
</table>
</div>
}
Here is the Model js code
var myData = angular.module('MyData', []);
Here is the controller JS code
myData.controller("DataController", function($scope) {
$scope.newUser = "";
$scope.addUser = function() {
$http.post("/Home/AddUser/", { newUser: $scope.newUser }).success(function (result) {
alert(result.success);
}).error(function(data) {
console.log(data);
});
};
});
Here is the post method inside controller which i am calling through angular js
[HttpPost]
public JsonResult AddUser(string name)
{
var db = new SchedulerEntities();
db.Users.Add(new User {Name = name});
db.SaveChanges();
return null;
}
I am adding an entry into DB from controller method but nothing is happening...
I think you need to declare $http in the function:
myData.controller("DataController", function($scope, $http) {
$scope.newUser = "";
$scope.addUser = function() {
$http.post("/Home/AddUser/", { newUser: $scope.newUser })
.success(function (result) {
alert(result.success);
}).error(function(data) {
console.log(data);
});
};
});
Related
I have a bootstrap modal instance that i have opened from parent controller , now i have added method on checkbox checkedValue that i am trying to invoke from child controller but i am getting error Cannot read property 'attuid' of undefined at ChildScope.$scope.checkedValue (newUserModal.controller.js:22) Any idea how can i invoke method in child controller ?
newUserModal.html
<tr ng-repeat="user in userList track by $index">
<td st-ratio="20">{{user.attuid}}</td>
<td st-ratio="30">{{user.firstName}} {{user.lastName}}</td>
<td st-ratio="15" ng-bind-html="user.type"></td>
<td st-ratio="15">{{user.email}}</td>
<td><input type="checkbox" ng-model="user.selected" ng-click="checkedValue(user)"> </td>
<!--<td st-ratio="20" class="text-right">
<button type="button" ng-click="editUser($index, user)" class="btn btn-primary">
Approve
</button>
</td>-->
</tr>
parent.controller.js
$scope.newUserListModal = function () {
$scope.modalInstance = $uibModal.open({
templateUrl: 'app/access/accessModal/newUserModal.html',
controller: 'AccessModalCtrl',
size: 'lg'
});
$scope.modalInstance.rendered.then(function () {
$rootScope.$broadcast('show-user-list',$scope.userList);
});
/*$scope.modalInstance.result.then(function(selectedUsers) {
console.log(selectedUsers);
});*/
}
child.controller.js
angular.module('angularModelerApp')
.controller('AccessModalCtrl', function ($scope,$uibModalInstance,toastr) {
var selectedUsers = [];
$scope.$on('show-user-list',function(e,data){
$scope.userList = data;
});
$scope.checkedValue = function(user){
$scope.selectedUsers = $scope.selectedUsers || [];
if(user.selected){
$scope.selectedUsers.push({ attuid: $scope.user.attuid,
firstName: $scope.user.firstName,
lastName: $scope.user.lastName,
email:$scope.user.email
});
console.log($scope.selectedUsers);
}
};
});
I am trying to update data in the database using angular in Laravel 4 but the data is'nt get inserted, and a blank value is getting stored in to the database. Please find the bug and try to insert the passed value insteed of blank value.
JS File
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.updateFunction = function(updateId) {
$http.get("http://localhost/crud/public/registration_update_page/" + updateId).then(function successCallback(response) {
console.log('successCallback');
console.log(response);
alert("Row with id " + updateId + ", updated..!");
}, function errorCallback(response) {
console.log('errorCallback');
console.log(response);
});
};
});
.PHP File
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h2>Registration</h2><br/>
<table border=1>
<tr><td>Name:</td><td><input type="text" ng-model="nam" name="nam"><br/></td></tr>
<tr><td>Email:</td><td><input type="email" ng-model="email" name="email"><br/></td></tr>
<tr><td>Password:</td><td><input type="password" ng-model="password" name="password"><br/></td></tr>
<tr><td>City:</td><td><input type="text" ng-model="city" name="city"><br/></td></tr>
<tr><td><button ng-click="insertFunc()" type="submit">Submit</button></td></tr>
</table>
</div>
</form>
<table style="width:100%" border=1>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
<th>City</th>
<th>Update</th>
<th>Delete</th>
</tr>
<tr ng-init='show = true' ng-repeat="x in query" ng-hide='!show'></div>
<!-- ng-hide will work when it is true in condition -->
<td>{{x.id}}</td>
<td><input type="text" value="{{x.name}}" name="edited_name"></td>
<td><input type="text" value="{{x.email}}" name="edited_email"></td>
<td><input type="text" value="{{x.password}}" name="edited_password"></td>
<td><input type="text" value="{{x.city}}" name="edited_city"></td><br/>
<td><input type="submit" ng-click="updateFunction(x.id);" value="Update"></td>
<td><button ng-click="deleteFunction(x.id);show = false">Delete</button></td>
<!-- !show==false means !false i.e., true -->
</tr><div>
</body>
</html>
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Session;
use Redirect;
class NewController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function registration_update_function(Request $request)
{
$updateId = $request->id;
$edited_name = $request->edited_name;
$edited_city = $request->edited_city;
$users1 = DB::table('angular_registration')->where('id', '=', $updateId)->update(['city' => $edited_city]);
}
}
Try with post method and following code and pass full x object / scope and x.id in this function updateFunction(x, x.id);
Angular Code
var req = {
method: 'POST',
url: 'http://localhost/crud/public/registration_update_page/',
data: { x: x, id = x.id }
}
$http(req).then(function(){
//Success
}, function(){
});
On server side PHP
print_r($_POST);
I solved this problem myself
This works for ANGULAR.JS with Laravel 4 to run insert,update,delete and select queries of the MySql DataBase.
VIEW
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h2>Registration</h2><br/>
<table border=1>
<tr><td>Name:</td><td><input type="text" ng-model="nam" name="nam"><br/></td></tr>
<tr><td>Email:</td><td><input type="email" ng-model="email" name="email"><br/></td></tr>
<tr><td>Password:</td><td><input type="password" ng-model="password" name="password"><br/></td></tr>
<tr><td>City:</td><td><input type="text" ng-model="city" name="city"><br/></td></tr>
<tr><td><button ng-click="insertFunc()" type="submit">Submit</button></td></tr>
</table>
</div>
</form>
<table style="width:100%" border=1>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
<th>City</th>
<th>Update</th>
<th>Delete</th>
</tr>
<tr ng-init='show = true' ng-repeat="x in query" ng-hide='!show'></div>
<!-- ng-hide will work when it is true in condition -->
<td>{{x.id}}</td>
<td>{{x.name}}<input type="text" ng-model="edited_name"></td>
<td>{{x.email}}<input type="text" ng-model="edited_email"></td>
<td>{{x.password}}<input type="text" ng-model="edited_password"></td>
<td>{{x.city}}<input type="text" ng-model="edited_city"></td><br/>
<td><input type="submit" ng-click="updateFunction(x.id,edited_name,edited_email,edited_password,edited_city);" value="Update"></td>
<td><button ng-click="deleteFunction(x.id);show = false">Delete</button></td>
<!-- !show==false means !false i.e., true -->
</tr><div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
$scope.deleteFunction = function(deleteId)
{
$http.get("http://localhost/crud/public/registration_delete_page/"+deleteId)
.then(function successCallback(response)
{
console.log('successCallback');
console.log(response);
alert("Row with id "+deleteId+", deleted..!");
},
function errorCallback(response)
{
console.log('errorCallback');
console.log(response);
});
};
$scope.updateFunction = function(updateId,edited_name,edited_email,edited_password,edited_city)
{
$http.get("http://localhost/crud/public/registration_update_page/"+updateId+"/"+edited_name+"/"+edited_email+"/"+edited_password+"/"+edited_city)
.then(function successCallback(response)
{
//$scope.edited_name = edited_name;
console.log('successCallback');
console.log(response);
alert("Row with id "+updateId+", updated..!");
},
function errorCallback(response)
{
console.log('errorCallback');
console.log(response);
});
};
$scope.insertFunc = function() {
$http({
method : 'POST',
url : 'http://localhost/crud/public/registration_data_page',
data : {nam:$scope.nam,email:$scope.email,password:$scope.password,city:$scope.city}
}).then(function successCallback(response) {
console.log('successCallback');
console.log(response);
}, function errorCallback(response) {
console.log('errorCallback');
console.log(response);
});
}
$http({method:'GET', url:'http://localhost/crud/public/registration_json_page'}).success(function(response){
$scope.query = response;
});
});
</script>
</body>
</html>
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Session;
use Redirect;
class NewController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function registration_data_function(Request $request)
{
echo $nam_value = $request->nam;
echo $email_value = $request->email;
echo $password_value = $request->password;
echo $city_value = $request->city;
$reg = DB::table('angular_registration')->insert(['name' => $nam_value, 'email' => $email_value, 'password'=>$password_value, 'city'=>$city_value]);
}
public function registration_json_function(Request $request)
{
$query = DB::select('select * from angular_registration');
return response($query);
}
public function registration_function(Request $request)
{
$query = DB::select('select * from angular_registration');
return view('registration');
}
public function registration_delete_function(Request $request)
{
$deleteId = $request->id;
return $users = DB::table('angular_registration')->where('id', '=', $deleteId)->delete();
}
public function registration_update_function(Request $request)
{
echo $updateId = $request->id;
echo $edited_name = $request->edited_name;
echo $edited_email = $request->edited_email;
echo $edited_password = $request->edited_password;
echo $edited_city = $request->edited_city;
$users1 = DB::table('angular_registration')->where('id', '=', $updateId)->update(['name' => $edited_name,'email' => $edited_email,'password' => $edited_password,'city' => $edited_city]);
}
}
ROUTE
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::auth();
Route::get('/registration', 'NewController#registration_function');
Route::post('/registration_data_page', 'NewController#registration_data_function');
Route::get('/registration_json_page', 'NewController#registration_json_function');
Route::get('registration_delete_page/{id}', 'NewController#registration_delete_function');
Route::get('registration_update_page/{id}/{edited_name}/{edited_email}/{edited_password}/{edited_city}', 'NewController#registration_update_function');
Iam new to AngularJS and now facing an issue with uirouter multiple views. Searched for various examples,but couldn’t find a solution. Hope you will help.
I have a submit function inside controller in nested view. When a user clicks on submit, the subt_click() has to be invoked and an url has to be created based on the date provided and should call data from that url and display in a table.
<div ng-controller="MyController as ctrl">
<form class="form-horizontal">
<div class="form-group">
<div class="col-sm-5">
<p class="input-group">
<input type="text" class="form-control" datetime-picker="yyyy-MM-dd HH:mm" ng-model="dates.date3" is-open="ctrl.open.date3" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="ctrl.openCalendar($event, 'date3')"><i class="fa fa-calendar"></i></button>
</span>
</p>
</div>
</div>
</form>
<a ui-sref=".submit" class="btn btn-info" ng-click="subt_click()">Submit</a>
</div>
Below is how I have declared states and called the subt_click().
app.js:
var wc = angular.module('wc', ['ui.router','ui.bootstrap', 'ui.bootstrap.datetimepicker']);
wc.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/posts');
$stateProvider
.state('tab', {
url: '/tab1',
templateUrl: 'tab.html'
})
.state('tab.submit', {
url: '/submit',
templateUrl: 'tab-submit.html',
//controller: 'MyController'
})
.state('tabs', {
url: '/tabs',
templateUrl: 'tabs.html',
});
});
wc.controller('MyController', function ($scope, $http, $location, $filter) {
var that = this;
var in10Days = new Date();
in10Days.setDate(in10Days.getDate() + 10);
$scope.dates = {
date3: " ",
date4: " "
};
this.dates = {
date3: new Date(),
date4: new Date(),
};
this.open = {
date3: false,
date4: false,
};
// Disable weekend selection
this.disabled = function (date, mode) {
return (mode === 'day' && (new Date().toDateString() == date.toDateString()));
};
this.dateOptions = {
showWeeks: false,
startingDay: 1
};
this.timeOptions = {
readonlyInput: false,
showMeridian: false
};
this.dateModeOptions = {
minMode: 'year',
maxMode: 'year'
};
this.openCalendar = function (e, date) {
that.open[date] = true;
};
$scope.format = 'yyyy-MM-dd%20HH:mm';
debugger;
$scope.subt_click = function () {
var date = $filter("date")($scope.dates.date3, $scope.format);
$http.get("URLpartA"+date+"URLpartB")
.success( function(response) {
debugger
$scope.condition = response.Table
console.log(response)
});
};
});
tab-submit.html:
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in condition">
<td>{{x.ID}}</td>
<td>{{x.Name}}</td>
</tr>
</tbody>
</table>
Here is a plunk to check the code: plunker:http://plnkr.co/edit/3Iyao5aOt2tY7Ze104dp?p=preview.
the displayed table is empty and not the data from url(URL am using is from local host).There are no errors on console and from console.log(response) I could see the array objects from url.
Am not sure where this has went wrong. Will be really grateful if anyone can help!!
Check this plunker. I've added a controller, a dummy service to fetch data and used the service in resolve to inject data into the controller.
Here I am Trying to Login with user credientials
if user is valid , I want to pass UserName,LastloginTime,Role values to another page using angular js
<form role="form" ng-app="MyApp" ng-controller="MasterController">
<div class="form-group">
<label>
Username</label>
<input type="text" class="form-control" placeholder="Username" required ng-model="username" />
</div>
<div class="form-group">
<label>
Password</label>
<input type="password" class="form-control" placeholder="Password" required ng-model="password" />
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="remember">
Remember my Password
</label>
</div>
<input type="button" value="Submit" ng-click="GetData()" class="btn btn-danger" />
<%--<button type="button" class="btn btn-danger" ng-click="GetData()">Submit</button>--%>
<span ng-bind="Message"></span>
</form>
js file here
$scope.GetData = function () {
debugger;
var data = { UserName: $scope.username, Password: $scope.password };
$http.post("api/Test/CheckUsername", data)
.success(function (data, status, headers, config) {
if (data != "") {
$scope.Employees = data;
window.location.href = "EmployeeMaster";
//$scope.Reporting = data;
}
else {
alert("Invalid Credientials");
}
});
}
I want to display values in a master page
<table class="table">
<tr ng-repeat="Emp in Employees">
<th>User </th>
<td>:</td>
<td>{{Emp.username}}</td>
</tr>
<tr>
<th>Designation </th>
<td>:</td>
<td>{{Emp.RoleName}}</td>
</tr>
<tr>
<th>Last Login </th>
<td>:</td>
<td>{{Emp.LastLogin}}</td>
</tr>
</table>
How can i pass the values login page to Home page?
I suggest creating a service to store your global data:
myApp.factory('DataService', function() {
var user = {
name: '',
role: ''
// and so on
};
return {
user: user
};
});
Just inject this to all your controllers and set and retrieve the data you need:
myApp.controller('MyCtrl', function($scope, DataService) {
// make your DataService available in your scope
$scope.DataService = DataService;
});
This lets you bind models globally to the DataService.
Check out angular-storage A Storage done right for AngularJS. It is great for storing user info/tokens/ any object.
Key Features
Uses localStorage or sessionStorage by default but if it's not available, it uses ngCookies.
Lets you save JS Objects
If you save a Number, you get a Number, not a String
Uses a caching system so that if you already have a value, it won't get it from the store again.
https://github.com/auth0/angular-storage
There is lot of ways of to achieve this
1) Use $rootscope like you use $scope like
$rootscope.userName = ""
Inject the $rootscope dependency in the controller where you want to show it and create an object name Employee and fill it with $rootscope.
2) use constant like
module.constant("userData", data);
Inject the userData dependency in the controller where you want to show it and create an object name Employee and fill it with userData.
3) You can use service/factory and save the data in localstorage/sessionstorage
to transfer data between pages, you can use stateParams:
in the routes file:
$stateProvider
.state('employeeMasterState', {
url: '/employeeMasterUrl/:employeeData',
templateUrl: 'info/employeeMaster.tpl.html',
controller: 'employeeMasterCtrl',
controllerAs: 'employeeMasterCtrlAs'
});
js:
$scope.GetData = function () {
debugger;
var data = { UserName: $scope.username, Password: $scope.password };
$http.post("api/Test/CheckUsername", data)
.success(function (data, status, headers, config) {
if (data != "") {
this.state.go('employeeMasterState',{employeeData:data});
}
else {
alert("Invalid Credientials");
}
});
}
in the next page js:
constructor($scope, $statePArams){
$scope.empData = $stateParams.data;
}
You can create a service or a factory to share data between webpages. Here is the documentation
I'm trying to create a sigle-page app that contains shop list, in every shop card is the link to another view that contains table with products.
A shop looks like:
shop = {
id: 1,
name: "foo",
description: 'bar',
products: [item1, itemn];
};
app.js:
angular
.module('lightpointTestApp', [
'ngCookies',
'ngRoute',
'ui.sortable'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/products/:shopID', {
templateUrl: 'views/products.html',
controller: 'ProductsCtrl'
})
.otherwise({
redirectTo: '/'
});
});
Main.html view where are shop list:
<h3>Shop list</h3>
<div class="row shopsContainer" ui-sortable ng-model="shops">
<div class="col-lg-3 shopCard" ng-repeat="shop in shops">
<button class="btn close cardClose" ng-click="removeShop($index)">×</button>
<div class="cardNumber">{{ shops.indexOf(shop) + 1 }}</div>
<div class="cardHeader">{{ shop.name }}</div>
<div class="cardBody">
{{ shop.address }}<br />
{{ shop.hours }}<br />
View {{ shop.products.length }} products
</div>
</div>
</div>
<div class="row">
<input type="text" ng-model="newShop.name" placeholder="Shop name" class="col-lg-3" />
<input type="text" ng-model="newShop.address" placeholder="Shop address" class="col-lg-3" />
<input type="text" ng-model="newShop.hours" placeholder="Shop hours" class="col-lg-3" />
<button class="btn btn-primary col-lg-3" type="button" ng-disabled="!newShop.name || !newShop.address || !newShop.hours" ng-click="addShop()">Add Shop</button>
</div>
</span>
</div>
</div>
products.js - controller for products page
angular.module('lightpointTestApp')
.controller('ProductsCtrl', function ($scope, $routeParams, shops) {
$scope.shopList = shops;
$scope.shop = {};
$scope.getShop = function (id) {
for (var i = 0; i < $scope.shopList.length; i++) {
if ($scope.shopList[i].id === id) {
return $scope.shopList[i];
}
}
return null;
};
var shopID = $routeParams.shopID;
$scope.shop = $scope.getShop(shopID);
})
products.html where is the table with products
<h2>{{ shop.name }}</h2>
<table class="table table-hover">
<tr>
<th>Product Name</th>
<th>Product Description</th>
</tr>
<tr ng-repeat="product in shop.products">
<td> {{ product.name }} </td>
<td> {{ product.description }} </td>
</tr>
</table>
The problem is that products.html doesn't bind with products.js and show something like {{shop.name}} and an empty table.
P.S. I think that products.js isn't correct, but I tried everything to do it well.
Thanks.
You have a parameter shops in ProductsCtrl, but there is nothing that will pass a value for it, so it is going to be null. You set the value of $scope.shopList to it, and then try to iterate over a NULL array, so you get an exception.
You can store the values of shops in a service, and then pass them around your app via injection. You can initialize their values within main.js, or within the service itself, and then the values will be available if you inject them into ProductsCtrl, something like
angular.module('lightpointTestApp')
.controller('ProductsCtrl', ['$scope', '$routeParams', 'shopsService',
function ($scope, $routeParams, shopsService) {
$scope.shopList = shopService;
$scope.shop = {};
$scope.getShop = function (id) {
for (var i = 0; i < $scope.shopList.length; i++) {
if ($scope.shopList[i].id === id) {
return $scope.shopList[i];
}
}
return null;
};
var shopID = $routeParams.shopID;
$scope.shop = $scope.getShop(shopID);
}]);
shopsService could look something like
angular.module('lightpointTestApp')
.service('shopsService', function() {
return [
// add whatever fields you need here from code in main.js
{ name: 'shop1', address: 'addr1' },
{ name: 'shop2', address: 'addr2' }
];
});
Where are your shop objects coming from? You are passing in shop, in products.js but not referencing it in the code. You should also use $q to use promises for async data. Also use the filter() function rather than a for loop to find the shop by shopId.
Are you hitting an API with shops or storing a local json for now?
With angular, you should separate your data logic manipulation in a factory or service as such:
productService.js
angular.module('lightpointTestApp')
.factory('shopService',function($http, $q){
var shops = [];
return {
getShops: function () {
var deferred = $q.defer();
$http.get('<path to product.json or api>').success(function(data){
shops = data;
deferred.resolve(data);
})
return deferred.promise;
},
getShopById: function(shopID) {
var deferred = $q.defer();
deferred.resolve(shops.filter(function(chain){
return chain.id === shopID;
})[0]);
return deferred.promise;
}
}
});
product.js
angular.module('lightpointTestApp')
.controller('ProductsCtrl', function ($scope, $routeParams, $q,shopService) {
$scope.shopList = [];
$scope.shop = {};
var shopID = $routeParams.shopID;
shopService.getShops.then(function(shops){
$scope.shopList = data;
})
$scope.getShopById = function(shopID) {
shopService.getShopById(shopID).then(function(shop){
$scope.shop = shop;
});
}
});