How to trigger ng-repeat in Angularjs with MVC application..? - angularjs

i'm creating an application in AngularJS with MVC
i write code in AdminCtrl.js is:
var adminModule = angular.module('angApp', []);
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
//*****get data from Product table
$scope.products = {};
GetAdmin();
function GetAdmin() {
$http({
method: 'GET',
url: '/Admin/GetAdmin',
datatype:'HTML',
}).success(function data() {
$scope.products = data.result;
})
}
}]);
i'm able to get data as collection from back end now using $scope i'm binding it to my view as:
<div id="divTest" ng-controller="AdminCtrl">
<div ng-repeat="item in products">
Prod_ID:{{item.Prod_ID}}
Prod_Name:{{item.Prod_Name}}
Prod_Price:{{item.Prod_Price}}
Prod_Desc:{{item.Prod_Desc}}
</div>
</div>
on the view i'm not able to bind this data using ng-repeat, but this data is visible on console.
please any one help me to figure out the issue what i'm missing.
Thanks in advance.

i did only a little bit mistake, i was binding ng-app to but in the sense it should be bind with now it's working.
my new code like as .....
<body ng-app="angApp">
<script src="Scripts/app/AdminCtrl.js"></script>
<div id="alert" class="alert"></div>
<div ng-controller="AdminCtrl">
<div class="admin-login">
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
</div>
</div>

change
.. }).success(function data() {
$scope.products = data.result;
})..
to
.. }).success(function (data) {
$scope.products = data.result;
})..
ie:
var adminModule = angular.module('angApp', []);
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
//*****get data from Product table
$scope.products = {};
GetAdmin();
function GetAdmin() {
$http({
method: 'GET',
url: '/Admin/GetAdmin',
datatype:'HTML',
//data needs to be inside bracket
}).success(function (data) {
$scope.products = data.result;
})
}
}]);

Related

ng-repeat not updating when ng-click function clicked

I have a GET function to list names, and another function that is triggered by an ng-click, that needs to update the ng-repeat where the lists of names are being at displayed by the get function. But it is not working. This is my code:
Container where the GET function displays:
<div class="container names-container" ng-controller='namesCtrl'>
<div ng-repeat='name in names.pData'>
<div class="name-box chiuv">
<p class="name-name">{{ name.name }} {{ name.last_name }}</p>
<p class="name-date">{{ name.date}}</p>
</div>
</div>
Search modal with the ng-click
<div class="output">
<input type="text" class="form-control" name="output" id="nameH" ng-model="inputName" placeholder="Search by name">
</div>
<div class="hebk"></div>
<button class="search-btn" ng-click="searchName()">SEARCH</button>
Functions
var fetch = angular.module('myapp', []);
fetch.controller('namesCtrl', ['$scope', '$http', function($scope, $http) {
$scope.getNames = function() {
$http({
method: 'get',
url: '<?= base_url(); ?>/display/getNames'
}).then(function successCallback(response) {
// Assign response to users object
$scope.names = response.data;
});
}
$scope.getNames();
$scope.searchName = function() {
$scope.names = '';
$http({
method: 'post',
data: {
name: $scope.inputName
},
url: '<?= base_url(); ?>/display/searchNames'
}).then(function successCallback(response) {
// Assign response to users object
$scope.names = [];
$scope.names = response.data;
});
}
}]);

Spinner Loading with AngularJS

I wanted to make Spinner should appear when user clicks on Submit Button and Spinner should stop once the AJAX POST and GET request completed
Can you Please help me know How I make my below Angular Code to implement the feature.
Below is the Example I saw for Spinner in Angular
Demo
Below is my AngularJS code .
var app = angular.module("myApp", ["ngTable"]);
app.controller("Controller", ["$scope", "$http", "$window",
function ($scope, $http, $window) {
$scope.firstFunction = function () {
$http({
method: 'POST',
url: 'mainDeviceSite.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
accountnumber: $scope.accountnumber
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
$scope.cellularIPAddressValue = response.data.devices;
console.log($scope.cellularIPAddressValue);
//$scope.secondFunction(data);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
$scope.secondFunction = function () {
$http({
method: 'POST',
url: 'BEPEvents.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
accountnumber: $scope.accountnumber
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
var x2js = new X2JS();
$scope.aftCnv = x2js.xml_str2json(response.data);
$scope.bepValues = $scope.aftCnv.EEPEvents.BlobData;
console.log($scope.bepValues);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
}
]);
HTML Code
<div class="example">
<div class="col-md-12">
<div class="row">
<div class="input-group form-search">
<input type="text" ng-model="accountnumber" name="accountnumber" class="form-control search-query" placeholder="Enter Account Number">
<span class="input-group-btn">
<button type="submit" ng-click="firstFunction();secondFunction()" class="btn btn-primary">Submit</button>
</span>
<span id="message">{{message}}</span>
</div>
</div>
</div>
</div>
Try Following solution
This applicable for all http request that are use in angular controller. When you call http request then spinner and progress bar you shows
Demo
Refer this angular-loading-bar.
include the loading bar as a dependency for your app. If you want animations, include ngAnimate as well. note: ngAnimate is optional
angular.module('myApp', ['angular-loading-bar', 'ngAnimate'])
include the supplied JS and CSS file (or create your own CSS to override defaults).
<link rel='stylesheet' href='build/loading-bar.min.css' type='text/css' media='all' />
<script type='text/javascript' src='build/loading-bar.min.js'></script>
Hope this is help you

Why won't my service register?

I tried creating a service in angularjs but I keep getting angular.js:10467 Error: [ng:areq] Argument 'MainController' is not a function, got undefined.
html:
<div ng-controller="MainController">
<form name="searchUser" method="post">
<input ng-model="username" type="search" placeholder="Find"/>
<input type="submit" value="Search" ng-click="search(username)" />
</form>
You are searching for: {{username}}
<hr />
<div ng-repeat="(key,value) in data">
{{ key + " : " + value}}
</div>
</div>
<script src="lib/angular/angular.js"></script>
<script src="js/app.js"></script>
<script src="services/Screamer.js"></script>
my app.js:
angular.module('NoteTaker', []); // dependcies in array.
angular.module('NoteTaker', []).controller('MainController', function(screamer, $log, $http, $scope, $interval){
$http({
method : 'GET',
url: 'https://api.github.com/users/' + $scope.username
}).then(function(response){
console.log(response);
$scope.data = response.data;
}, function(response){
console.log(response);
});
my service in service.js
(function() {
'use strict';
angular.module('NoteTaker', []).factory('screamer', function(){
return {
say: "blahbalh"
};
});
}());
angular.module(name, dependencies) creates a new module. If you want to add to an existing one, use angular.module(name):
angular.module('NoteTaker', []); // dependcies in array.
angular.module('NoteTaker')
.controller('MainController', function(screamer, $log, $http, $scope, $interval) {
$http({
method: 'GET',
url: 'https://api.github.com/users/' + $scope.username
}).then(function(response) {
console.log(response);
$scope.data = response.data;
}, function(response) {
console.log(response);
});
});
// service.js
(function() {
'use strict';
angular.module('NoteTaker').factory('screamer', function() {
return {
say: "blahbalh"
};
});
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="NoteTaker" ng-controller="MainController">
<form name="searchUser" method="post">
<input ng-model="username" type="search" placeholder="Find" />
<input type="submit" value="Search" ng-click="search(username)" />
</form>
You are searching for: {{username}}
<hr />
<div ng-repeat="(key,value) in data">
{{ key + " : " + value}}
</div>
</div>
I create a new module on line 1, and add the controller & service to it.
tcooc answered your question, but I'll try to make it a little easier to understand:
app.module('myModule', ['dep1', 'dep2']); // passing an array creates a NEW module
Access the newly created module by calling the same method, but without the array of dependencies:
app.module('myModule')
.controller('MyController')
.service('MyService')
.factory('MyFactory');
Or, just attach everything to the first module call:
app.module('myModule', ['dep1', 'dep2'])
.controller('MyController', function(...) {})
.service('MyService', function(...) {})
.factory('MyFactory', function(...) {});
Also, it helps to write dependency injection like this:
MyController.$inject = ['$scope', '$location', '$log'];
function MyController($scope, $location, $log) {
}
MyService.$inject = ['$http'];
function MyService($http) {
}
This makes it clear what is getting injected where. And it makes your code much more readable, since you can now write this:
app.module('myModule', ['dep1', 'dep2'])
.controller('MyController', MyController)
.service('MyService', MyService);

Angularjs list not refreshing on form submit using MEAN

Some what new to the MEAN stack. Currently I'm reworking an small app I did through codeschool to be full MEAN stack.
The app created can be seen here
Code School app
In rewriting the app using the MEAN stack after submitting the form I must refresh the page to see the city added to the list. What do I need to fix so I don't need to refresh the page for the new Item to be added to the list?
If I'm missing any relevant code below here is my git hub link
git hub link
Here is my code:
angular.module('Cityapp').controller('CityIndexController', function(City, $scope){
$scope.cities = City.query();
window.sc = $scope;
});
angular.module('Cityapp').controller('CityCreateController', function(City, $scope, $http){
$scope.city = new City();
$scope.saveCity = function(city){
$http({
method: 'POST',
url: '/city',
data: city})
.success( function(data, status, headers, config){
console.log($scope.city);
console.log(data);
console.log($scope.city);
}).
error(function(data,status,headers,config){
jQuery('.alert').show();
console.log('nope');
});
};
});
<form ng-controller="CityCreateController">
<legend> New City</legend>
<input for="City-group" name="City" id="City" type="text" ng-model="city.city" placeholder="City Name">
<input for="City-group" name="desc" id="desc" type="text" ng-model="city.desc" placeholder="Description">
<input type="submit" class="btn btn-default" ng-click="saveCity(city)"/>
</form>
<ul ng-controller="CityIndexController" class="city-list">
<li ng-repeat="city in cities">
<a href="#">
{{city.city}}</a></li>
</ul>
It should looks something like that
;(function() {
function Cities($http) {
function City() {
}
City.prototype.save = function() {
return $http.post('/api/city', this);
};
City.cities = [];
City.add = function(city) {
city.save().then(function() {
City.cities.push(city);
});
};
City.getAll = function() {
$http.get('/api/cities').then(function(response) {
City.cities = response.data.map(function(data) {
return new City(data);
});
return cities;
});
};
return City;
}
function CityCreateController(Cities) {
var mv = this;
mv.city = new Cities();
mv.saveCity = function() {
Cities.add(mv.city);
};
}
function CityIndexController($scope, Cities) {
var mv = this;
$scope.$watchCollection(function() {
return Cities.cities;
}, function(cities) {
mv.cities = cities || [];
});
Cities.getAll();
}
angular
.module('app', [])
.factory('Cities', ['$http', Cities])
.controller('CityCreateController', ['Cities', CityCreateController])
.controller('CityIndexController', ['$scope', 'Cities', CityIndexController]);
})();
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<meta charset="utf-8">
</head>
<body ng-app="app">
<form ng-controller="CityCreateController as mv">
<legend> New City</legend>
<input for="City-group" name="City" id="City" type="text" ng-model="mv.city.city" placeholder="City Name">
<input for="City-group" name="desc" id="desc" type="text" ng-model="mv.city.desc" placeholder="Description">
<input type="submit" class="btn btn-default" ng-click="mv.saveCity()"/>
</form>
<ul ng-controller="CityIndexController as mv" class="city-list">
<li ng-repeat="city in mv.cities">
<a href="#">
{{city.city}}</a></li>
</ul>
</body>
</html>
Found a simple fix
angular.module('Cityapp').controller('CityCreateController', function(City, $scope, $http){
$scope.cities = City.query();
$scope.city = new City();
$scope.saveCity = function(city){
$http({
method: 'POST',
url: '/city',
data: city})
.success( function(data, status, headers, config){
$scope.cities.push({city: $scope.city.city,
desc: $scope.city.desc});
}).
error(function(data,status,headers,config){
jQuery('.alert').show();
console.log('nope');
});
};
});
Just added the
$scope.cities.push({city: $scope.city.city,
desc: $scope.city.desc});
to the .success. Works like it should. Now on to my next issue.

ng-click event is not firing on button click?

i'm creating web application in Angularjs i write code in separate .js file for log in from database
is is execute on page load but not triggering on button click,
my .js code is:
var adminModule = angular.module('angApp', []);
//Defining a Angular Controller
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
Login();
function Login(U_Name, U_PWD) {
debugger;
//Defining the $http service for login the admin user
$http({
method: 'POST',
url: '/Admin/IsAuthenticate',
data: { User_Name: U_Name, User_PWD: U_PWD }
}).success(function (result) {
if (result == true) {
alert('user is valid');
}
else {
alert('unauthorised access!');
}
}).error(function (error) {
//Showing error message
$scope.status = 'Unable to connect' + error.message;
});
}
}]);
and my view as what i'm using for binding this using Angularjs here is an issue above code is working on page load but don't work on button click, the code i use is:
<div class="admin-login" ng-controller="AdminCtrl" ng-app="angApp">
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
anyone please help me what i miss here so i'm not able to trigger ng-click event on button click
thanks in advance.
Your Login function needs to be on a scope. Right now, its essentially a private function:
$scope.Login = function () {
...
}
assign function to a scope variable.
var adminModule = angular.module('angApp', []);
//Defining a Angular Controller
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.Login = function (U_Name, U_PWD) {
debugger;
//Defining the $http service for login the admin user
$http({
method: 'POST',
url: '/Admin/IsAuthenticate',
data: { User_Name: U_Name, User_PWD: U_PWD }
}).success(function (result) {
if (result == true) {
alert('user is valid');
}
else {
alert('unauthorised access!');
}
}).error(function (error) {
//Showing error message
$scope.status = 'Unable to connect' + error.message;
});
}
$scope.Login();
}]);
Edited:
try to use this html code,but i am not sure.it may be that both ng-init and ng-controller are in same div and ng-controller load first after that ng-init :
<div ng-app="angApp">
<div class="admin-login" ng-controller="AdminCtrl" >
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
</div>

Resources