I have created one function
<button data-toggle="modal" ng-click="edit(school.school_ID)" data-target="#edit-data" class="btn btn-primary">Edit</button>
pass to AngularJS controller
$scope.edit = function(id)
{
$http({
method : 'GET',
url: 'mycontroller/myfun',
}).then(function(data){
console.log(data);
$scope.form = data;
});
};
accessing in mycontroller/myfun
public function myfun(id)
{
$q = $this->db->get_where('tablename', array('school_ID' =>
id));
echo json_encode($q->row());
}
Where is the problem
Below is app.js file contain myApp module. I am facing issue with $scope variable not updated on view file which is rendered using $state.
I am calling showArticles function on ng-change event from one of view file which got rendered using $state.go statement. This view rendered after user login. All code snap given below. Also facing same issue after AJAX success response $scope not getting updated on view file.
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('settings', {
url: '/settings',
templateUrl: 'templates/setting.html',
controller: 'adminCtrl',
})
.state('profile', {
url: '/profile',
templateUrl: 'templates/profile.html',
controller: 'adminCtrl',
})
.state('account', {
url: '/account',
templateUrl: 'templates/account.html',
controller: 'adminCtrl',
cache: false
})
.state('articleList', {
url: '/articles',
controller: 'adminCtrl',
cache: false,
templateUrl: 'templates/articleList.html',
})
.state('addArticle', {
url:'/addArticle',
templateUrl : 'templates/addArticle',
controller: 'adminCtrl',
cache: false
})
$urlRouterProvider.otherwise('/settings');
});
myApp.run(function($rootScope, $state, $location, AuthenticationService){
//array of route that dont need authentication
var routeThatDontNeedAuth = ['/settings'];
var routeClean = function(route)
{
//alert(route); alert();
if(routeThatDontNeedAuth.indexOf(route) !== -1){ alert('aaa');
return false;
}
else{
return true;
}
}
$rootScope.$on('$stateChangeStart', function(event, next, current){
if(routeThatDontNeedAuth.indexOf($location.url()) < 0)
{
if(!AuthenticationService.isLoggedIn()){
//$state.go('settings');
//alert('not logged in and page is not login page');
}
}
});
});
myApp.factory('AuthenticationService', ['$http', '$state', function($http, $state){
return{
isLoggedIn: function(){ alert('Aut ser called');
$http({
url: 'http://127.0.0.1:8081/cUlI',
method: 'GET'
}).then(function(response){
alert('testtt');console.log(response);
if(!response.data.loggedIn)
{
$state.go('settings');
}
})
}
};
}]);
myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'getArticleData', function($scope, $http, $state, getArticleData){
$scope.addArticle = function(){
$state.go('addArticle');
}
// get website list
$scope.showArticles = function(){
/*$scope.articleList = 'this is default article scope value';
alert($scope.articleList)
$scope.$applyAsync(function() {
$scope.articleList = "Another value rest"; alert($scope.articleList)
});*/
$http({
method: "GET",
url: "http://127.0.0.1:8081/articleList",
params: {
website:$scope.website
}
}).then(function(responseData){
if(responseData.data.status == 'success')
{
console.log('test dataaa');
console.log(responseData);
alert('page should modified')
alert('This is test');
$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
$scope.artLs = "I am testt model";
$state.go('articleList', 'cache: false');
}
})
}
$scope.adminLogin = function(){
var uname = $scope.username;
var pass = $scope.password ;
alert(uname+'--'+pass);
$http({
method : "GET",
url : "http://127.0.0.1:8081/adminLogin",
params: {
username : uname,
pwd: pass
}
}).then(function(response) {
console.log('succes',response);
if(response.data.status == 'success')
{
$http({
method: "GET",
url: "http://127.0.0.1:8081/webSiteList"
}).then(function(responseData){
if(responseData.data.status == 'success')
{
$scope.sara = 'testsara';
$scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
console.log('scope website data', $scope.websiteData);
$state.go('account', 'cache: false');
}
});
}
else
{
}
}, function(response) {
console.log('error',response)
});
}
}]);
showArticles functions get called on ng-change event from account view:
<div id="main-container" class="col-md-12 container" >
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="main-body">
<div class="content">
<div class="col-md-2"></div>
<div class="col-md-8">
<h2 class="text-center">Article Listing page modified</h2>
<div class="vt-add-article">
<button type="button" ="btn btn-default text-center" ng-click="addArticle();">Add</button>
</div>
<div class="vt-article-list">
{{articleList}}
<br>
{{artLs}} -- exp value
</div>
</div>
<div class="col-md-2"></div>
</div>
</div>
</div>
<div class="col-md-1"></div>
</div>
Main Index .html file :
<html>
<head>
<meta charset="utf-8">
<title>Welcome to Vidarbha Tigers Content Panel</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="/angularp/router/css/admin.css" />
<script src="/angularp/router/js/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="/angularp/router/js/app.js"></script>
</head>
<body ng-app="myApp" ng-controller="adminCtrl">
<header>
<div class="col-md-12">
<div class="col-md-1"></div>
<div class="vt-header-content col-md-10">
<div class="vt-header-logo">
<!--<img src="/images/logo.jpg" class="img-rounded" alt="Vidarbha Tiger"> -->
</div>
<div class="vt-header-tag"><h2><!--Vidarbha Tigers--></h2></div>
</div>
<div class="col-md-1"></div>
</div>
<hr/>
</header>
<div ui-view></div>
</body>
</body>
</html>
Kindly let me know if I am missing anything in my code. I am new to angular js and facing few issues which are unknown to me
ok, I understand your issue. Your $scope variable is getting reset everytime you call a view. Hence, you dont see any value. You will have to save the value and then retrieve it when your view gets loaded. I have updated your code below, try and let me know if it works or not
SOLUTION 1:
Create one more factory:
myApp.factory('persistService', ['$rootScope', function($rootScope){
var articleList = '';
return{
saveArticleList: function(data) {
articleList = data;
},
getArticleList: function() {
return articleList;
}
};
}]);
Then in your controller include the above service and save the articleList and when you go to your new view, intialize your articleList using the 'persistService' as below :
myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'persistService', 'getArticleData', function($scope, $http, $state, getArticleData, persistService){
//Initialize your articleList
$scope.articleList = persistService.getArticleList();
$scope.addArticle = function(){
$state.go('addArticle');
}
// get website list
$scope.showArticles = function(){
/*$scope.articleList = 'this is default article scope value';
alert($scope.articleList)
$scope.$applyAsync(function() {
$scope.articleList = "Another value rest"; alert($scope.articleList)
});*/
$http({
method: "GET",
url: "http://127.0.0.1:8081/articleList",
params: {
website:$scope.website
}
}).then(function(responseData){
if(responseData.data.status == 'success')
{
console.log('test dataaa');
console.log(responseData);
alert('page should modified')
alert('This is test');
//Save your data
persistService.setArticleList('This is a test');
//$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
$scope.artLs = "I am testt model";
$state.go('articleList', 'cache: false');
}
})
}
$scope.adminLogin = function(){
var uname = $scope.username;
var pass = $scope.password ;
alert(uname+'--'+pass);
$http({
method : "GET",
url : "http://127.0.0.1:8081/adminLogin",
params: {
username : uname,
pwd: pass
}
}).then(function(response) {
console.log('succes',response);
if(response.data.status == 'success')
{
$http({
method: "GET",
url: "http://127.0.0.1:8081/webSiteList"
}).then(function(responseData){
if(responseData.data.status == 'success')
{
$scope.sara = 'testsara';
$scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
console.log('scope website data', $scope.websiteData);
$state.go('account', 'cache: false');
}
});
}
else
{
}
}, function(response) {
console.log('error',response)
});
}
}]);
Let me know if this helps!
EDIT::
SOLUTION 2:
There is another way you can accomplish the same just by making a change in your controller code. See below code:
myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'getArticleData', function($scope, $http, $state, getArticleData){
//Initialize your articleList
$scope.articleList = $scope.articleList || {};
$scope.addArticle = function(){
$state.go('addArticle');
}
// get website list
$scope.showArticles = function(){
/*$scope.articleList = 'this is default article scope value';
alert($scope.articleList)
$scope.$applyAsync(function() {
$scope.articleList = "Another value rest"; alert($scope.articleList)
});*/
$http({
method: "GET",
url: "http://127.0.0.1:8081/articleList",
params: {
website:$scope.website
}
}).then(function(responseData){
if(responseData.data.status == 'success')
{
console.log('test dataaa');
console.log(responseData);
alert('page should modified')
alert('This is test');
//Save your data
$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
$scope.artLs = "I am testt model";
$state.go('articleList', 'cache: false');
}
})
}
$scope.adminLogin = function(){
var uname = $scope.username;
var pass = $scope.password ;
alert(uname+'--'+pass);
$http({
method : "GET",
url : "http://127.0.0.1:8081/adminLogin",
params: {
username : uname,
pwd: pass
}
}).then(function(response) {
console.log('succes',response);
if(response.data.status == 'success')
{
$http({
method: "GET",
url: "http://127.0.0.1:8081/webSiteList"
}).then(function(responseData){
if(responseData.data.status == 'success')
{
$scope.sara = 'testsara';
$scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
console.log('scope website data', $scope.websiteData);
$state.go('account', 'cache: false');
}
});
}
else
{
}
}, function(response) {
console.log('error',response)
});
}
}]);
is the alert that you have put printing the correct value?
Based on my understanding I think you set the articleList on ng-change called in one view file. After that you change state and go to another view file where you expect to see the updated articleList value which you set in the previous view. But, I think what may be happening is that when you navigate to the second view your controller might be getting reloaded and your $scope.articleList gets reset. Try printing the value of articleList before and after you change view.
To prevent this you can try using angular services to save the articleList value
I'm trying to load a function on a link click, which works perfectly. Then angularjs does its magic until it arrives on the point where it shows the user feedback. I need to refresh the page after deleting an item, but it simply won't refresh.
Here's my href:
<a ng-click="deleteGroup(group.id)" target="_self">
<img src="img/deleteGroupIcon.png" width="45px"/></a>
here's my Controller:
$scope.deleteGroup = function ($groupId) {
$http({
method: 'POST',
url: apiUrl + 'group/delete',
data: {'groupId': $groupId}, // pass in data as strings
//headers: {'Content-Type': 'application/x-www-form-urlencoded'}
// set the headers so angular passing info as
// form data (not request payload)
})
.success(function (data) {
if (!data.success) {
//$route.reload();
alert('groep is verwijderd');
} else {
$scope.group = data;
//$state.go('userDetail', {'user_id' : $userId});
}
});
};
and my html:
<div class="searchResults" ng-repeat="group in groups | searchForUser:searchString">
<div class="manageGroupWrapper">
<a class="normal" href="#">
<div class="newName h3">
{{group.title}}
</div>
<div class="newProfile">
<img ng-src="{{group.image}}" width="200px"/>
</div>
<div class="imageWrapper">
<a ui-sref="add_group" class="editGroupIcon"><img src="img/editGroupIcon.png" width="50px"/></a>
<a ng-click="deleteGroup(group.id)" target="_self"><img src="img/deleteGroupIcon.png" width="45px"/></a>
</div>
</a>
</div>
Your $scope.deleteGroup function should remove its target group from the $scope.groups so the content of the ng-repeat is automatically updated and does not display the group anymore.
$scope.deleteGroup = function (group) {
$http({
method: 'POST',
url: apiUrl + 'group/delete',
data: {'groupId': group.$groupId}, // pass in data as strings
//headers: {'Content-Type': 'application/x-www-form-urlencoded'}
// set the headers so angular passing info as
// form data (not request payload)
}).success(function(data) {
$scope.groups.splice($scope.groups.indexOf(group));
});
};
To force refreshing the page with uiRouter you can use $state.go(target, params, {reload: true}).
$scope.deleteGroup = function (group) {
$http({
method: 'POST',
url: apiUrl + 'group/delete',
data: {'groupId': group.groupId}, // pass in data as strings
//headers: {'Content-Type': 'application/x-www-form-urlencoded'}
// set the headers so angular passing info as
// form data (not request payload)
}).success(function(data) {
// This will reload the current state with the same stateParams
$state.go($state.current.name, $stateParams, {reload: true});
});
};
Without the ngcontroller alias, I can fetch the data. However, when with alias, I can't. What is my mistake here?
HTML tags:
<div style="padding: 10px" id="content_dv" ng-controller="displaytopic_ctrl as f">
<div class="topic_dv" ng-repeat="t in f.topic">
<p>{{ t.MEMBER_NAME }}</p>
</div>
</div>
in app.js:
.controller('displaytopic_ctrl', ['$http', function($http) {
$http({
method: 'get',
url: api_url + 'get_topic_list.php',
data: {
type: 'all'
}
}).success(function(d){
if(d.t=='p'){
this.topic = d.topic;
}
}).error(
function(){
console.log('Query error');
});
}]);
Due to the way JavaScript closures work, the this variable that you are using in your success callback is not the controller. The most commonly used mechanism to solve this is to create an alias for the controller which you can reference inside your callbacks.
For Example:
.controller('displaytopic_ctrl', ['$http',
function($http) {
var controller = this;
$http({
method: 'get',
url: api_url + 'get_topic_list.php',
data: {
type: 'all'
}
}).success(function(d) {
if (d.t == 'p') {
controller.topic = d.topic;
}
}).error(
function() {
console.log('Query error');
});
}
]);
I am trying to filter an array (courses) by a property, FacilityId.
I am getting a response back for all of my $http calls in my controller which is as follows:
function holeIndexController($scope, $http) {
$scope.facilities = [];
$scope.courses = [];
$scope.holes = [];
getFacilities();
getCourses();
getHoles();
function getFacilities() {
$http({
method: 'GET',
url: '/api/facility'
}).
success(function(result) {
$scope.facilities = result;
}).error(function () {
console.log("Error: " + result.ExceptionMessage);
alert("Could not load facilities");
});
}
$scope.courseByFacility = function (facilities) {
return function(courses) {
return course.facilityId === facility.facilityId;
};
};
function getCourses() {
$http({
method: 'GET',
url: '/api/course'
}).
success(function (result) {
$scope.courses = result;
}).error(function (result) {
console.log("Error: " + result.ExceptionMessage);
alert("Could not load courses");
});
}
function getHoles() {
$http({
method: 'GET',
url: '/api/hole'
}).
success(function(result) {
getFacilities();
$scope.holes = result;
}).error(function(result) {
console.log("Error: " + result.ExceptionMessage);
alert("Could not load courses");
});
}
}
And my HTML is as follows:
<div data-ng-repeat="f in facilities">
Facility: {{f.Name}}
<div data-ng-repeat="c in courses | filter: coursesByFacility">
Course: {{c.Name}}
</div>
</div>
What is the best way to filter courses by their respective FacilityId's?
Pass the facility into the filter function, like:
<div ng-repeat="c in courses | filter:coursesByFacility(f)">
Also, your coursesByFacility function takes a courses parameter, but then you're trying to act upon course (no s). Change this to this:
$scope.coursesByFacility = function(facility) {
return function(course) {
return course.facilityId === facility.facilityId;
}
}
See this jsbin
Edit: Didn't realize the jsbin link was going to strip all the code so you can't see it. Anyways, just view the source, it's minimal and easy to read
You could create a function called getCoursesByFacility() which has a facilityId parameter. The function should iterate through the list of courses and build an array of courses with that facilityId, then return the list. You would then need to call the function from your javascript. Something like this should work:
<div data-ng-repeat="f in facilities">
Facility: {{f.Name}}
<div data-ng-repeat="c in getCoursesByFacility(f.facilityId)">
Course: {{c.Name}}
</div>
</div>