Function not getting called using ng-click - angularjs

Inside the controller I have a login() function which should be called using ng-click like this:
<body ng-app="angularoauthexampleApp">
<div class="social-buttons">
<i class="fa fa-facebook"></i> Facebook
<i class="fa fa-google" ng-click="login()"></i> Google
</div>
</body>
MainJS:
angular.module('angularoauthexampleApp', [
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/afterlogin', {
templateUrl: 'views/afterlogin.html',
controller: 'AboutCtrl'
})
.when('/access_token=:accessToken', {
template: '',
controller: function ($location, $rootScope) {
var hash = $location.path().substr(1);
var splitted = hash.split('&');
var params = {};
for (var i = 0; i < splitted.length; i++) {
var param = splitted[i].split('=');
var key = param[0];
var value = param[1];
params[key] = value;
$rootScope.accesstoken = params;
}
$location.path("/afterlogin");
}
})
.otherwise({
redirectTo: '/'
});
});
Controller:
angular.module('angularoauthexampleApp')
.controller('MainCtrl', ['$scope', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.login=function() {
alert("main");
var client_id="343625411797-hcm0impil8l1mughb8ma2jj966um05bp.apps.googleusercontent.com";
var scope="email";
var redirect_uri="http://localhost:9046/RTH_Sample4/app/";
var response_type="token";
var url="https://accounts.google.com/o/oauth2/auth?scope="+scope+"&client_id="+client_id+"&redirect_uri="+redirect_uri+
"&response_type="+response_type;
window.location.replace(url);
};
}]);
Nothing happens when I click the button on the form or event is not getting fired. I can't see anything wrong with code but some how its not working

MainCtrl gets loaded inside the views/main.html
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
this has to be loaded inside a ng-view directive in your root html.
Inside that html you can use the login().
Another way is to directly use the controller in the root html:
<body ng-app="angularoauthexampleApp">
<div class="social-buttons" ng-controller="MainCtrl">
<i class="fa fa-facebook"></i> Facebook
<i class="fa fa-google" ng-click="login()"></i> Google
</div>
</body>
Also, you have attached ng-click to the i element so you have to click the G icon for login() to work. Move it to the a element and you should be ok.

Related

ng-click does not work for linking to another view

I'm trying to link to a different page/view via ng-click and a function inside my controller. I don't do it with href because later it should be a right-click-event. But my code doesn't work. I've tried very much, and searched alot of pages but I can't find any solution. Thanks for your help :)
game.html
<div class="container" ng-controller="MainController">
<div class="handcards" ng-repeat="card in stdCards">
<a ng-click="goToCardDetail()" href="">{{ card.name }}</a>
</div>
</div>
MainController.js
app.controller('MainController', ['$scope', 'stdcards', '$location', function($scope, stdcards, $location) {
stdcards.success(function(data) {
$scope.stdCards = data;
});
$scope.goToCardDetail = function() {
$location.path('#/cards/0');
};
}]);
app.js
'use strict';
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainController',
templateUrl: 'templates/game.html'
})
.when('/cards/:id', {
controller: 'CardController',
templateUrl: 'templates/card.html'
})
.otherwise({
redirectTo: '/'
});
});
You don't need to include the # when you are calling $location.path(). So it should just be
$location.path('/cards/0');

could not modify view after calling ajax from controller using a factory

I have a demo app through which I want to display all countries data in a page(view) using angularjs.
Here is my code:
MyApp.js
var app = angular.module("MyApp", [ 'ui.bootstrap',
'ngRoute',
'MyControllers',
'MyFactory' ]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/home', {
controller: 'MyController',
templateUrl: 'resources/modules/homeView/homeView.jsp'
})
.when('/view1', {
controller: 'MyController',
templateUrl: 'resources/modules/view1/view1.jsp'
})
.when('/view2', {
controller: 'MyController',
templateUrl: 'resources/modules/view2/view2.jsp'
})
.otherwise({redirectTo: '/home'});
}]);
MyControllers.js
var controllers = angular.module('MyControllers', []);
controllers.controller('MyController', ['$scope', 'Factory',
function($scope, Factory) {
$scope.countries = [];
$scope.showme = false;
$scope.CountryDetailsClick = function() {
var responsePromise = Factory
.getResponse("http://localhost:12345/DemoNew/getCountryList");
responsePromise.success(function(data, status, headers,
config) {
$scope.countries = data;
console.log("countryList size = " + $scope.countries.length);
$scope.showme = true;
});
responsePromise.error(function(data, status, headers,
config) {
alert("AJAX failed");
});
}
}]);
MyFactory.js
var myFactory = angular.module('MyFactory', []);
myFactory.factory('Factory', function($http) {
return {
getResponse : function(url) {
return $http.get(url);
}
}
});
View1.jsp
<body ng-view>
<h1 class="page-header">View1</h1>
{{countries.length}}
</body>
View2.jsp
<body ng-view>
<h1 class="page-header">View2</h1>
{{showme}}
</body>
homeView.jsp
<body ng-view>
<h1 class="page-header">Home</h1>
index.jsp
<body ng-app="MyApp" ng-controller="MyController">
<nav class="navbar navbar-default navbar-static-top" role="navigation"
style="margin-bottom: 0">
Country Details
Country Rate Plans
</nav>
<div id="page-wrapper" ng-view>
</div>
</body>
Now I am getting on console as :-
countryList size = 268
which is correct, I am using spring for backend. I am able to fetch data from the database.
But in View1 I get:
0
Also in View2 I get:
false
That means I am not able to reflect the fetched data to the view. Please help :(
===============================================================
After suggestions given by rob, i changed the following:
I changed my MyFactory.js to:
var myFactory = angular.module('MyFactory', []);
myFactory.factory('Factory', function($http) {
var current = {};
var factory = {
getResponse: function(urlReq){
var data = $http({method: 'GET', url: urlReq}).then(function (result){
current = result.data;
}, function (result){
alert("ERROR: No data returned");
});
},
getList: function(){
return current;
}
}
return factory;
});
And MyControllers.js to:
var controllers = angular.module('MyControllers', []);
controllers.controller('MyController',
function($scope, Factory) {
$scope.CountryDetailsClick = function() {
Factory.getResponse("http://localhost:12345/DemoNew/getCountryList");
}
});
controllers.controller('MyController3',
function($scope, Factory) {
console.log("in controller3");
});
controllers.controller('MyController2',
function($scope, Factory) {
console.log("in controller2");
$scope.countries = Factory.getList();
$scope.showme = true;
});
MyApp.js
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/home', {
controller: 'MyController',
templateUrl: 'resources/modules/homeView/homeView.jsp'
})
.when('/view1', {
controller: 'MyController3',
templateUrl: 'resources/modules/view1/view1.jsp'
})
.when('/view2', {
controller: 'MyController2',
templateUrl: 'resources/modules/view2/view2.jsp'
})
.otherwise({redirectTo: '/home'});
}]);
View2.jsp
<body ng-view>
<h1 class="page-header">View2</h1>
{{showme}}
{{countries}}
</body>
When I click on Country Details, I get "true" and an empty array, but when I click Country Details after clicking Country Rate Plans, it works perfectly fine.
Please find the flaw.!!
You are using the same controller from index.jsp and from your views. So Angular is creating two instances of your controller each with it's own scope. You are calling CountryDetailsClick() from the ng-controller in index.jsp's scope but you are trying to show the value of countries.length from the view's scope.
If you want to share some functionality or state between different controllers (e.g. your CountryDetailsClick() function) then put it in a service.

ng-click inside ui-router not firing

i have a ngClick that is not firing.
this is my view:
<div ng-repeat="(key,val) in user[docParam]">
{{key}}<input type='text' class="form-control" name="{{key}}" ng-model="user[docParam][key]">
</div>
<div class="col-xs-6 col-xs-offset-3" ng-if="nextDoc(docParam)">
<a ui-sref="form.{{nextDoc(docParam)}}" class="btn btn-block btn-info">
Proceed To {{nextDoc(docParam)}} &nbsp <span class="glyphicon glyphicon-circle-arrow-right"></span>
</a>
</div>
<div class="col-xs-6 col-xs-offset-3" ng-if="nextDoc(docParam)==false">
<a ng-click="save(user)" class="btn btn-block btn-info">
save &nbsp <span class="glyphicon glyphicon-circle-arrow-right"></span>
</a>
</div>
and this is app.js :
var $stateProviderRef = null;
var $urlRouterProviderRef = null;
var app= angular.module('app', [
//'ui.bootstrap',
'ui.router',
'ui.bootstrap',
'flow',
'controllers',
'services',
'filters',
'directives',
'xeditable',
'ngResource',
])
.run(['$rootScope', '$state', '$stateParams',
function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
])
.controller('AController', ['$scope', function($scope) {} ])
.controller('SController', ['$scope', function($scope) {} ])
.config(['$locationProvider', '$stateProvider', '$urlRouterProvider', '$httpProvider',
function($locationProvider, $stateProvider, $urlRouterProvider, $httpProvider) {
// XSRF token naming
$httpProvider.defaults.xsrfHeaderName = 'x-dt-csrf-header';
$httpProvider.defaults.xsrfCookieName = 'X-CSRF-TOKEN';
//$httpProvider.interceptors.push('httpInterceptor');
$stateProvider
.state('form', {
url: "/form",
templateUrl: '../partials/form/form.html',
controller:'formController',
});
$urlRouterProvider.deferIntercept();
$urlRouterProvider.otherwise('/form');
$locationProvider.html5Mode({
enabled: false
});
$stateProviderRef = $stateProvider;
$urlRouterProviderRef = $urlRouterProvider;
}])
.run(['$q', '$rootScope', '$http', '$urlRouter',
function($q, $rootScope, $http, $urlRouter) {
var $state = $rootScope.$state;
$http
.get("../lib/modules.json")
.success(function(data) {
angular.forEach(data, function(value, key) {
var getExistingState = $state.get(value.name);
if(getExistingState !== null){
return;
}
var state = {
"url": value.url,
"parent": value.parent,
"abstract": value.abstract,
"views": {}
};
angular.forEach(value.views, function(view) {
state.views[view.name] = {
templateUrl: view.templateUrl,
controller:'formController',
};
});
$stateProviderRef.state(value.name, state);
});
// Configures $urlRouter's listener *after* your custom listener
$state.go("form.personalInfo");
});
}
]);
controller:
.controller('formController', function($scope,DocParamData,$state,$http) {
'use strict';
$scope.docParam = $state.current.name.split('.');
$scope.docParam = $scope.docParam[1];
// we will store all of our form data in this object
$scope.saveUser = function(user) {
$http.post('/users', user).success(function(v){
return user;
}).error(function(err) {
if(err.field && err.msg) {
// err like {field: "name", msg: "Server-side error for this username!"}
$scope.editableForm.$setError(err.field, err.msg);
} else {
// unknown error
$scope.editableForm.$setError('name', 'Unknown error!');
}
});
};
the problem is with ng-click, it doesnt fire. not even a simple alert. ive allready tried everything in the threads, and i have no idea what is wrong.
i remember that there is some way to get a onclick to work with the scope..but cant find the right syntax..
You probably have errors in the console that you're not aware of.
I'm pretty sure dynamic {{...}} expression syntax is not supported by the ui-sref directive. See this issue.
Also name="{{key}}" should be ng-attr-name="{{key}}"

UI-Router don't route with param

I use UI-Router. I have a first controller
vehicuels.controller.js:
'use strict';
angular.module('autoPrivilegeApp')
.controller('VehiculesCtrl', function ($scope,$http, $state) {
$scope.awesomeThings = [];
$http.get('/api/cars').success(function (awesomeThings) {
$scope.message = awesomeThings;
});
// Show Car detail
$scope.showCarDetail = function (_id) {
$state.go('vehiculeDetail', {id: _id});
};
});
vehicules.js:
'use strict';
angular.module('autoPrivilegeApp')
.config(function ($stateProvider) {
$stateProvider
.state('vehicules', {
url: '/vehicules',
templateUrl: 'app/vehicules/vehicules.html',
controller: 'VehiculesCtrl'
});
});
vehicules.html:
<div class="col-md-12">
<div ng-repeat="car in message">
<button class="medium bouton bleu" ng-click="showCarDetail(car._id);">
{{ car._id }}
</button>
<br/><br/><br/><br/>
</div>
</div>
I want to pass id to my second controller
vehiculeDetail.controller.js:
'use strict';
angular.module('autoPrivilegeApp')
.controller('VehiculeDetailCtrl', function ($scope,$stateParams ) {
$scope.message = $stateParams.instanceID;
});
vehiculeDetails.js:
'use strict';
angular.module('autoPrivilegeApp')
.config(function ($stateProvider) {
$stateProvider
.state('vehiculeDetail', {
url: '/vehiculeDetail/{id}',
templateUrl: 'app/vehiculeDetail/vehiculeDetail.html',
controller: 'VehiculeDetailCtrl'
});
});
vehiculeDetail.html:
<div class="col-md-12">
This is the vehiculeDetail id {{message}}.
</div>
I have use the yeoman generator --> generator-angular-fullstack
my problem is that I do not get my id in my controller VehiculeDetailCtrl.
What is wrong?
The $stateParams uses name as they are defined in url:
$stateProvider
.state('vehiculeDetail', {
url: '/vehiculeDetail/{id}', // here we name our param as 'id'
So, we have to use now the name id instead of the instanceID
.controller('VehiculeDetailCtrl', function ($scope,$stateParams ) {
//$scope.message = $stateParams.instanceID;
$scope.message = $stateParams.id;

AngularJS controller as syntax "this" is not $scope

I'm new to angularjs and I'm trying to employ the styles outlined from this post: https://github.com/johnpapa/angular-styleguide. When using the var vm = this style, rather than $scope, the vars I'm trying to bind to in the template are unavailable. Inspecting vm in the console shows an empty object, not the same as $scope.
/* index.js */
angular.module('myApp', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngResource', 'ngRoute', 'ui.bootstrap', 'loginModule', 'sidebarModule', 'jm.i18next'])
.value('baseUri', "/myApp/api")
.config(config)
.run(function($rootScope, $injector) {
$injector.get("$http").defaults.transformRequest = function(data, headersGetter) {
if ($rootScope.oauth !== undefined) {
console.log($rootScope.oauth);
headersGetter()['Access-Token'] = $rootScope.oauth.access_token;
}
if (data) {
return angular.toJson(data);
}
};
});
function config($routeProvider, $i18nextProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/my-module-login/login.html',
controller: 'loginController',
conrollerAs: 'vm' // not available in template
})
.otherwise({
redirectTo: '/'
});
/* login.module.js */
angular.module('loginModule', ['utils']);
/* login.controller.js */
(function(){
'use strict';
angular.module('loginModule')
.controller('loginController', login);
login.$inject = ['$rootScope', '$scope', 'credsFactory', 'loginFactory'];
function login($rootScope, $scope, credsFactory, loginFactory) {
var vm = this; //empty object
vm.user = {};
vm.login = doLogin;
function doLogin(user) {
//user creds
var creds = {
userName: user.username,
password: user.password
};
loginFactory.login(creds)
.success(function (data) {
credsFactory.setCreds(data);
$scope.status = 'Logged in user!';
$scope.creds = creds;
var storageCreds = credsFactory.getCreds();
$rootScope.oauth = {};
$rootScope.oauth.access_token = storageCreds.accessToken;
window.location.hash = "#/logged-in";
}).
error(function(error) {
$scope.status = 'Unable to login user: ' + error.message;
});
}
}
})();
/* login.html */
<div class="form-group form-group-sm">
<div class="text-center">
<!-- how to access vm, {{vm.login(user)}} doesn't work -->
<button type="button" class="btn btn-default" id="login-submit" ng-i18next="button.cancel" ng-click="login(user)"></button>
</div>
</div>
You can declare the controllerAs when setting up the route - there is a typo in your example. (The name does not have to be the same as in loginController function)
Route:
$routeProvider
.when('/', {
templateUrl: 'app/my-module-login/login.html',
controller: 'loginController',
controllerAs: 'vm'
})
View:
<button ng-click="vm.login(user)"></button>
Also, when using "var vm = this;" in the controller function, you do not need to inject $scope. Instead of $scope in doLogin success function:
vm.status = 'Logged in user!';

Resources