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)}}   <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   <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}}"
Related
I was using angular directive and it was working fine. But suddenly it stopped working and i don't know why. Here is my code:
<div id="main" data-ng-controller="Controller" data-ng-app="app">
<div class="stars">
<star-rating value="{{item.Value.Rate}}"></star-rating>
</div>
</div>
My angular code is here:
angular.module('app', ['ui.bootstrap']);
var app = angular.module('app', []);
app.directive('starRating', function () {
return {
scope: {
value: '='
},
template: '<div class="stars"><i class="fa fa-star" ng-repeat="r in entries"></i></div>',
controller: function ($scope) {
$scope.entries = _.range($scope.value);
}
}
});
app.controller('Controller', function ($scope, $location, $http) {
//
})
.config(function ($httpProvider, $locationProvider) {
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.post["Content-Type"] = "application/json;
charset=utf-8";
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
i really don't know what i'm missing.
I have a very strange issue. Using AngularJS 1.5.8. With previous versions it didn't work either. Functions like ng-bind, ng-model, ng-submit work fine.
Click on "Inschrijven" http://adr-opleiding.ismiami.com/, second step "Postcode" and enter e.g. 1000. It will display Amsterdam. I used a div element w/ ng-bind="city". If I use {{city}} it will always display {{city}}. I can't get it to update from a controller.
angular.module('app', []).controller('HomeController', ['$rootScope', '$scope', '$stateParams', function($rootScope, $scope, $stateParams) {
$scope.$on('$viewContentLoaded', function() {
$scope.app.settings.htmlClass = $stateParams.htmlClass.website;
$scope.app.settings.bodyClass = '';
});
}])
.controller('WizCtrl', ['$scope', '$http', function($scope, $http) {
$scope.city = '';
$scope.printCity = function(){
if($scope.postcode.length == 4) {
$http({
method: 'POST',
url: '/db/get.php',
data: { action: 'retCity', zip: $scope.postcode }
})
.then(function success(response) {
$scope.city = response.data.city;
}, function error(response) {
});
}
}
}]);
And here's the HTML:
<div class="form-group">
<label for="wiz-postcode" class="col-xs-4 control-label">Postcode:</label>
<div class="col-xs-3">
<input class="form-control" type="text" name="wiz-postcode" id="wiz-postcode" style="width: 80px;" placeholder="Postcode" ng-keyup="printCity()" ng-model="postcode" onblur="this.value=this.value.toUpperCase()" />
</div>
<div class="col-xs-5" ng-bind="city" style="padding-top: 8px; font-size: 1.1em;"></div>
</div>
At the very top of the HTML I have a div element w/ the controller:
<div ng-controller="WizCtrl">
So the question is how come that $scope variables work fine for everything except updating the view w/ a variable like this {{test}}
A new Google search "angularjs variables in braces not working" got me to AngularJS-Twig conflict with double curly braces from which I learned that w/ AngularJS you can set the symbols w/ the variables start and endSymbol
var app = angular.module('app')
.config(
[ '$controllerProvider', '$compileProvider', '$filterProvider', '$provide', '$interpolateProvider',
function ($controllerProvider, $compileProvider, $filterProvider, $provide, $interpolateProvider) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.directive;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
app.constant = $provide.constant;
app.value = $provide.value;
$interpolateProvider.startSymbol('::');
$interpolateProvider.endSymbol('::');
}
]);
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.
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!';
I'm downloading some data using firebase before presenting new controller's view, but the template "blinks" before showing the data. I have no idea why, it should show the data instantly without any delay. I've recorded it and marked each individual frame (http://i.imgur.com/pUsMCqX.gif). Console logs the data that resolve object returns. You can see that when data is being logged, the template is being shown with no data at frames 2 and 3.
Template:
<div ng-cloak class="wrapper select-character">
<div>
<div>
<h1>Select character</h1>
<div>
<button ng-click="createNewCharacter()">create new character</button>
</div>
characters' list
</div>
</div>
<div ng-repeat="character in characters">
<div>
Name: {{ character.name }}
<br>
Level: {{ character.level }}
<br>
<button ng-click="enterWorld(character.name)">Choose</button>
</div>
</div>
</div>
Controller:
'use strict';
angular.module('App')
.controller('SelectCharacterCtrl', function($scope, $firebaseSimpleLogin, $location, characters) {
$scope.createNewCharacter = function() {
$location.path("/create-character");
};
$scope.enterWorld = function(name) {
alert(name);
};
$scope.characters = characters;
});
App:
'use strict';
angular.module('App', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'firebase',
'angularfire.firebase',
'angularfire.login'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/log-in.html',
controller: 'LogInCtrl'
})
.when('/select-character', {
templateUrl: 'views/select-character.html',
controller: 'SelectCharacterCtrl',
resolve: {
characters: function($q, $timeout, $firebase, $firebaseSimpleLogin) {
var deferred = $q.defer();
var loginObj = $firebaseSimpleLogin(new Firebase("https://<id>.firebaseio.com"));
loginObj.$getCurrentUser()
.then(function(user) { // get login data
var userSync = $firebase(new Firebase('https://<id>.firebaseio.com/users/' + user.uid));
return userSync.$asObject().$loaded();
})
.then(function(user) { // get all characters
var promises = [];
angular.forEach(user.characters, function(name) {
var promise = $firebase(new Firebase('https://<id>.firebaseio.com/characters/' + name));
promises.push(promise.$asObject());
});
$q.all(promises).then(function(sth) {
console.log(sth);
deferred.resolve(sth);
});
});
return deferred.promise;
}
}
})
.when('/create-character', {
templateUrl: 'views/create-character.html',
controller: 'CreateCharacterCtrl'
})
});
Why does the template "blinks" with no data for 2 frames before updating the scope? Any ideas?
Since $asObject does not return a promise, your list of promises are immediately resolved (instead of after all the data is downloaded). Change your list to return promises too:
angular.forEach(user.characters, function(name) {
var promise = $firebase(new Firebase('https://<id>.firebaseio.com/characters/' + name));
promises.push(promise.$asObject().$loaded());
});