angular js not bind scope data after $http call - angularjs

i using the login via popup window in angular application. After popup i need to fill username and password , then i hit the sign in button , i ill get the json response , based on the response i have to show user account options menu using ng-show . for this case i m using following service and controller
my service code snippt
factory('services', ['$http', function ($http, logger) {
var ser = {};
ser.userLogin = function (data) {
return $http({
method: "post",
url: "login",
data: data,
async: true,
cache: false,
}).success(function (result) {
return result.data;
}
);
};
return ser;
}])
my controller code snippet
$scope.submitLogin = function () {
return services.userLogin($scope.login).then(function (data) {
var result = data.data;
if (result) {
console.log(result);
$scope.usercontrol = true;
console.log($scope.usercontrol);
ngDialog.close();
}
})
}
Template code
<ul ng-hide="usercontrol" class="nav navbar-nav navbar-right">
<li><a ng-click="signIn()"> <strong>Sign In</strong></a></li>
<li><a ng-click="signUp()"><strong>Sign Up</strong></a></li>
</ul>
<ul ng-show="usercontrol" class="nav navbar-nav navbar-right">
<li ng-class="{ active: isActive('/account')}"> <strong>My Account</strong></li>
<li><strong>Sign Out</strong></li>
</ul>
based on above code in my application working finely but not set $scope.usercontrol . any mistake i did?
demo plnkr.co/edit/EbfPjKWh6f4nwNcoqly1?p=preview

I have done some modification over the code.
Only thing is you might have not included the service in you controller function as a parameter.
html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#*" data-semver="1.3.1" src="//code.angularjs.org/1.3.1/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>SO Question</h1>
<div ng-controller="LoginCtrl">
<ul ng-hide="usercontrol" class="nav navbar-nav navbar-right">
<li><a ng-click="signIn()"> <strong>Sign In</strong></a></li>
<li><a ng-click="signUp()"><strong>Sign Up</strong></a></li>
</ul>
<div ng-hide="usercontrol">
<input type="text" ng-modal="login.username" placeholder="username">
<input type="password" ng-modal = "login.password" placeholder="password">
<button ng-click="submitLogin()">Sign IN</button>
</div>
<ul ng-show="usercontrol" class="nav navbar-nav navbar-right">
<li ng-class="{ active: isActive('/account')}"> <strong>My Account</strong></li>
<li><strong>Sign Out</strong></li>
</ul>
</div>
</body>
</html>
script.js
var app = angular.module('app', []);
app.controller('LoginCtrl', ['$scope', '$http', '$timeout', 'LoginService', function($scope, $http, $timeout, LoginService){
$scope.usercontrol = false;
$scope.submitLogin = function() {
LoginService.userLogin($scope.login).then(function (data) {
var result = data;
if (result) {
console.log(result);
$scope.usercontrol = true;
console.log($scope.usercontrol);
}
});
};
}]);
app.factory('LoginService', ['$http', function($http){
var ser = {};
ser.userLogin = function (data) {
return $http({
method: "GET",
url: "login.json",
data: data,
async: true,
cache: false,
}).success(function (result) {
return result.data;
}
);
};
return ser;
}]);
I have made a plunkr on this http://plnkr.co/edit/ZShhiNTu7KLY1b0t8LQG?p=preview
UPDATE
You have missed to add scope: $scope to continue in the ngDialog, and please check on the CSS issues.
http://plnkr.co/edit/ZShhiNTu7KLY1b0t8LQG?p=preview
UPDATE
I have forked your code http://plnkr.co/edit/J6i6QY4sO3ZzoEvbnzJ3?p=preview and changed 2 things, scope: $scope and for CSS issues I have changed the template into plain and removed controller.
ngDialog.open({
template: 'signinDialog',
scope: $scope,
className: 'ngdialog-theme-plain'
});

Related

Using AngularJS, how can I pass a clicked object property to a function?

Using AngularJS, I am creating a wizard. In order to navigate properly, the clicked wizardresult.Title needs to be passed into the function showpagetwo().
Here is the HTML:
<div ng-app="wizardApp">
<div ng-controller="MainCtrl">
<div ng-repeat="wizardresult in wizardresults">
<div id="initial" ng-if="wizardresult.RootItem =='Yes'">
<button type="button" class="btn btn-primary" ng-click="showpagetwo()">{{wizardresult.Title}}
...
</button>
</div>
<div id="pagetwo" style="display:none">
...
</div>
</div>
</div>
</div>
My JS:
function showpagetwo(){
console.log("Hello");
$("#pagetwo").fadeIn();
$( "#initial" ).hide()
}
var app = angular.module('wizardApp', []);
app.controller('MainCtrl', function($scope, $http, $q){
var supportList;
$(document).ready(function() {
$scope.getSupportList();
});
$scope.prepContext = function(url,listname,query){
var path = url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query;
return path;
}
$scope.getSupportList = function() {
supportList = $http({
method: 'GET',
url: this.prepContext(siteOrigin+"/divisions/testing","SupportList","?$orderBy=Title"),
headers: {
"Accept": "application/json; odata=verbose"
}
}).then(function(data) {
//$("#articleSection").fadeIn(2000);
console.log(data.data.d.results);
$scope.wizardresults = data.data.d.results;
});
};
});
I have tried ng-click="showpagetwo(wizardresult.Title)" and just ng-click="showpagetwo()"but the function is not firing at all either way.
What is my issue here?
You just need to put your callback function in the $scope and pass the argument you want to receive.
Something like this:
HTML:
<div class="test" ng-controller="Ctrl">
<button ng-click="myFn(wizardresult.Title);">click me</button>
<div>
JS:
var app = angular.module('app', []);
function Ctrl($scope) {
$scope.wizardresult = {Title: 'myname'};
$scope.myFn = function(param){
alert("Param: " + param);
};
}
Check this jsfiddle: http://jsfiddle.net/m1q4q4cm/
Add the function showpagetwo() inside controller.
var app = angular.module('wizardApp', []);
app.controller('MainCtrl', function($scope, $http, $q){
var supportList;
$(document).ready(function() {
$scope.getSupportList();
});
$scope.prepContext = function(url,listname,query){
var path = url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query;
return path;
}
$scope.showpagetwo= function(title){
console.log("Hello "+title);
$("#pagetwo").fadeIn();
$( "#initial" ).hide()
}
$scope.getSupportList = function() {
supportList = $http({
method: 'GET',
url: this.prepContext(siteOrigin+"/divisions/testing","SupportList","?$orderBy=Title"),
headers: {
"Accept": "application/json; odata=verbose"
}
}).then(function(data) {
//$("#articleSection").fadeIn(2000);
console.log(data.data.d.results);
$scope.wizardresults = data.data.d.results;
});
};
});
You cannot call a function outside your app directly with ng-click. The angular way of what you are trying to achieve will be like
Html
<div ng-app="wizardApp">
<div ng-controller="MainCtrl">
<div ng-repeat="wizardresult in wizardresults">
<div id="initial" ng-if="wizardresult.RootItem =='Yes'" ng-show="showThisDiv">
<button type="button" class="btn btn-primary" ng-click="showpagetwo(wizardresult.Title)">{{wizardresult.Title}}
...
</button>
</div>
<div id="pagetwo" ng-hide="showThisDiv">
...
</div>
</div>
</div>
</div>
Controller
app.controller('MainCtrl', function($scope, $http, $q){
$scope.showThisDiv = true
$scope.showpagetwo = function(wizardTitle){
$scope.showThisDiv = true
}
});
For the animation effects, you can use angular-animate library and add class="animate-show animate-hide" to divs for the fade effects.
For some reason if you want to use jquery, then just change the scope function to
$scope.showpagetwo = function(wizardTitle){
$("#pagetwo").fadeIn();
$( "#initial" ).hide()
}
Hope this will help.

Angular Scope issues with dynamic tab updates

I am trying to show angular Post data whenever a tab is clicked using ng-click event.
But it's not working.
What am i doing wrong here?.
First part of code works fine for switching Tabs, But i also want to show dynamic response when any tab is clicked & use it's tabNum as ?id=tabNum in ajax POST
angular.module('tabApp', [])
.controller('TabController', ['$scope', function($scope, $http) {
$scope.tab = 1;
$scope.setTab = function(newTab){
$scope.tab = newTab;
};
$scope.isSet = function(tabNum){
return $scope.tab === tabNum;
};
}]);
I HAVE PROBLEM WITH FOLLOWING CODE, WHERE SHOULD I PLACE IT ?
$http.get('http://localhost:8080/welcome.html?id=$tabNum')
.success(function(data, status, headers, config) {
$scope.tab = data;
})
.error(function(data, status, headers, config) {
// log error
}); }]);
this is my HTML page
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>MY
Reports
<link rel='stylesheet prefetch' href='https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.css'>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container" ng-app="tabApp">
<div class="row" ng-controller="TabController">
<div class="col-md-3">
<ul class="nav nav-pills nav-stacked">
<li ng-class="{ active: isSet(1) }">
<a href ng-click="setTab(1)">SHOW Manual Admins</a>
</li>
<li ng-class="{ active: isSet(2) }">
<a href ng-click="setTab(2)">SHOW ONE Admins</a>
</li>
<li ng-class="{ active: isSet(3) }">
<a href ng-click="setTab(3)">SHOW TWO Read Admins</a>
</li>
<li ng-class="{ active: isSet(4) }">
<a href ng-click="setTab(4)">SHOW THREE Admins</a>
</li>
<li ng-class="{ active: isSet(5) }">
<a href ng-click="setTab(5)">SHOW FOUR Read Admins</a>
</li>
<li ng-class="{ active: isSet(6) }">
<a href ng-click="setTab(6)">SHOW FIVE Read Admins</a>
</li>
</ul>
</div>
<div class="col-md-8">
<div class="jumbotron">
<div ng-show="isSet(1)">
<h1>CONTENT1</h1>
</div>
<div ng-show="isSet(2)">
<h1>CONTENT2</h1>
</div>
<div ng-show="isSet(3)">
<h1>CONTENT3</h1>
</div>
<div ng-show="isSet(4)">
<h1>CONTENT4</h1>
</div>
<div ng-show="isSet(5)">
<h1>CONTENT5</h1>
</div>
<div ng-show="isSet(6)">
<h1>CONTENT6</h1>
</div>
</div>
</div>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular.min.js'></script>
<script src="app.js"></script>
</body>
</html>
Hey as mentioned in my comment you can use a service for your http calls
.service('HttpService', ['$rootScope', '$http', 'Ls', 'CommonService', 'DateService', function ($rootScope, $http, Ls, CommonService, DateService) {
return {
CallService: function (url, callback) {
$http.get(url)
.success(function (data, status) {
callback(data, status);
}).error(function (data, status) {
callback(data, status);
});
}
}
});
Which can be called from the controller (dont forget to inject HttpService)
.controller('TabController', ['$scope', 'HttpService', function($scope, HttpService) {
$scope.tab = 1;
$scope.setTab = function(newTab){
$scope.tab = newTab;
HttpService.CallService('http://localhost:8080/welcome.html?id='+newTab, function (data) {
$scope.tabdata = data;
});
};
$scope.isSet = function(tabNum){
return $scope.tab === tabNum;
};
the whole would look like this
angular.module('tabApp', [])
.controller('TabController', ['$scope', 'HttpService', function($scope, HttpService) {
$scope.tab = 1;
$scope.setTab = function(newTab){
$scope.tab = newTab;
HttpService.CallService('http://localhost:8080/welcome.html?id='+newTab, function (data) {
$scope.tabdata = data;
});
};
$scope.isSet = function(tabNum){
return $scope.tab === tabNum;
};
}])
.service('HttpService', ['$rootScope', '$http', function ($rootScope, $http) {
return {
CallService: function (url, callback) {
$http.get(url)
.success(function (data, status) {
callback(data, status);
}).error(function (data, status) {
callback(data, status);
});
}
}
});
Mh maybe the get call maybe console log status and response

ng-click(s) does not work in partial view

I'm trying to render partial view on click, which has controller in it.
Layout/Index page :
<!DOCTYPE html>
<html lang="en" ng-app="AngularDemo">
<head>
..
</head>
<body>
<aside>
<ul class="nav nav-list" ng-controller="Navigations as nav">
<li class="">Home</li>
<li class=""> Feedbacks</li>
</ul>
</aside>
<section id="MainBody"></section>
</body>
</html>
controller.js
myApp.controller("Navigations", ["$compile", function ($compile) {
var $this = this;
this.showFeedbackDiv = function ($event) {
var compiledeHTML = $compile("<div load-Div></div>")($this);
$("#MainBody").append(compiledeHTML);
$(".Division").hide();
$("." + $(event.currentTarget).data("thisdiv")).show();
};
}]).directive('loadDiv', function () {
return {
templateUrl: '/Default/GetFeedbackView',
controller: 'Feedback'
};
});
myApp.controller("Feedback", ['AngService', '$element', function(AngService, $element) {
this.feedbackData = {};
var $this = this;
this.ShowFeedbacks = function () {
AngService.ShowFeedbacks().then(function (response) {
$this.allFeedbacks = JSON.parse(response.data);
console.log($this.allFeedbacks);
$("#ShowFeedbacksModal").modal({ backdrop: 'static', keyboard: false, show: true });
}, function (response) {
alert('Error in getting feedbacks');
});
};
}]);
partial View :
<div class="Division FedbackDiv" style="margin-top:40px" ng-controller="Feedback as fb">
<div class="page-header">
<h1>
Feedback form
<span style="cursor:pointer;" class="pull-right" ng-click="fb.ShowFeedbacks()"><i class="fa fa-adn"></i></span>
</h1>
</div>
<div class="row">
...
</div>
</div>
When i click on "show Feedbacks" nothing happens
error :
TypeError: a.$new is not a function
at g (angular.js:6970)
at M (angular.js:7618)
at angular.js:7854
at angular.js:12914
at h.$eval (angular.js:14123)
at h.$digest (angular.js:13939)
at h.$apply (angular.js:14227)
at p (angular.js:9493)
at J (angular.js:9678)
at XMLHttpRequest.t.onload (angular.js:9621)(anonymous function) # angular.js:11358
Should pass $scope in $compile; $scope should be injected into the controller; if you inspect the object this, it's not scope
instead of
var compiledeHTML = $compile("<div load-Div></div>")($this);
try
var compiledeHTML = $compile("<div load-Div></div>")($scope);
To inject $scope
myApp.controller('Navigations', ['$compile', '$scope', function ($compile, $scope) { ... }])
remove ng-controller="Feedback as fb from partial and add controllerAs : fb to loadDiv config
.directive('loadDiv', function () {
return {
templateUrl: '/Default/GetFeedbackView',
controller: 'Feedback',
controllerAs : 'fb'
};

Laravel 5 and AngularJS Data

I'm implementing AngularJS with Laravel and having some issues. My codes:
Route:
Route::get('/', function () {
return view('angular');
});
Route::get('/test', function () {
return User::all();
});
HTML/JS (test.blade.php):
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="userCtrl">
<ul>
<li ng-repeat="x in user">
#{{ x.email + ', ' + x.name }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('userCtrl', function($scope, $http) {
$http.get("/test")
.success(function(response) {
$scope.user = response.data;
console.log(response);
});
});
</script>
Whenever I run this I get a blank page but in my console:
Am I missing something here? Thank you.
check in console if it is returned valid in success: console.log(data);.
If yes try: $scope.user = angular.fromJson(data);

How do i can show form data after submit on other page using isolated scope directive?

I am new to angularjs,i make a sample app ,now i want to display data on next page when form is submitted using isolated scope directive .
my index.html:
<body ng-controller="mainController">
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">Angular Routing Example</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
<li><i class="fa fa-shield"></i> About</li>
<li><i class="fa fa-comment"></i> Contact </li>
</ul>
</div>
</nav>
<div id="main">
<!-- angular templating -->
<!-- this is where content will be injected -->
<div ui-view></div>
</div>
</body>
Directive:
var scotchApp = angular.module('scotchApp');
scotchApp.directive('homeData', function() {
return {
scope: {
info: '=fo'
},
templateUrl: 'homeDirective.html'
}
scotchApp.controller('MyFormCtrl', [function() {
this.user = {
name: '',
email: ''
};
this.register = function() {
// console.log('User clicked register', this.user);
alert(this.user.name + "-- " + this.user.email);
$scope.name = this.user.name;
};
}]);
})
how can i make possible this when someone submit the form the about page is displayed after clicking submit button and all form data i want to display there.
here is my plunker: http://plnkr.co/edit/D5S2c6rgycWFfsyfhN9J?p=preview
So based off of what you put into plunker and looking at your code I noticed a few issues.
First: You had your controller inside your directive causing none of the code within the directive to be run.
Your Code
var scotchApp = angular.module('scotchApp');
scotchApp.directive('homeData', function() {
return {
scope:{
info:'=fo'
},
templateUrl: 'homeDirective.html'
}
scotchApp.controller('MyFormCtrl', [function() {
this.user = {
name: '',
email: ''
};
this.register = function() {
// console.log('User clicked register', this.user);
alert(this.user.name+ "-- " +this.user.email);
$scope.name=this.user.name;
};
}]);
})
Update Code:
var scotchApp = angular.module('scotchApp');
scotchApp.directive('homeData', function() {
return {
scope:{
info:'=fo'
},
templateUrl: 'homeDirective.html'
};
});
scotchApp.controller('MyFormCtrl', [function() {
this.user = {
name: '',
email: ''
};
this.register = function() {
// console.log('User clicked register', this.user);
alert(this.user.name+ "-- " +this.user.email);
$scope.name=this.user.name;
};
}]);
Second: You need to add some way allowing your variables to talk between controllers. I used a service and passed it into both controllers
homeDirective.js
scotchApp.controller('MyFormCtrl', ['$scope', 'userService', function($scope, userService) {
$scope.userService = userService;
$scope.user = {
name: '',
email: ''
};
$scope.register = function() {
//sets the variables within the service
$scope.userService.setUserName($scope.user.name);
$scope.userService.setUserEmail($scope.user.email);
alert($scope.userService.getUserName() + "-- " + $scope.userService.getUserEmail());
};
}]);
//Service to be passes to the controllers
scotchApp.service('userService', function(){
var userService = {
user: {
'name': '',
'email': ''
},
getUser: function(){
return userService.user;
},
getUserName: function(){
return userService.user.name;
},
getUserEmail: function(){
return userService.user.email;
},
setUserName: function(name){
userService.user.name = name;
},
setUserEmail: function(email){
userService.user.email = email;
},
};
return userService;
});
script.js
scotchApp.controller('aboutController', ['$scope', 'userService', function($scope, userService) {
$scope.userService = userService;
$scope.user = $scope.userService.user;
$scope.message = 'Look! I am an about page.';
}]);
Third: Your HTML page had to be able to call the register function and move over to the about page.
homeDirective.html
<div class="jumbotron text-center" >
<h1>Home Page</h1>
<p>{{ message }}</p>
<form name="myForm" ng-controller="MyFormCtrl as ctrl">
Name: <input type="text" class="form-control" ng-model="user.name">
Email: <input type="email" class="form-control" ng-model="user.email">
<br/>
<a type="submit" ng-href="#about">
<button ng-click="register();" type="submit">Register</button>
</a>
</form>
</div>
Last: You should put your whole angular app in a self calling function like so
(function(){
var app = angular.module('app'[]);
//more code
})();
Here is the link to the plunk fork that I did for your code. Hopefully that all made sense.Link to Plunker
Good Luck!
Use Angular Services to share data between controllers.You can use services to organize and share code across your app.

Resources