Angular JS Button ng-click doesn't call method - angularjs

for now I read a lot of post for this problem, but none seems to have a solution.
In my angular app I created a new route with angular-fullstack:route
So here are my controller, template and config file:
controller:
'use strict';
(function() {
class AnmeldungCtrl {
constructor($http, $window, $uibModal, $state) {
}
searchUser(searchString) {
console.log("search Method");
if (searchString.isNaN()) {
this.state = "search";
console.log("search");
//TODO Search for name
}
else if (searchString >= 1000000) {
this.state = "anmeldung";
console.log("anmeldung");
//TODO Search for bar code
}
else {
this.state = "edit";
console.log("edit");
//TODO Search for Participant
}
}
}
angular.module('schwimmfestivalApp').controller('AnmeldungCtrl', AnmeldungCtrl);
})();
template:
<div>
<input type="text" ng-model="query" >
<button ng-click="ctrl.searchUser(query)">Search</button>
{{query}}
</div>
config file:
'use strict';
angular.module('schwimmfestivalApp')
.config(function ($stateProvider) {
$stateProvider
.state('anmeldung', {
url: '/anmeldung',
templateUrl: 'app/anmeldung/anmeldung.html',
controller: 'AnmeldungCtrl',
controllerAs: 'ctrl'
});
});
As I mention in my heading for some reason the method at the controller doesn't get called. And I have no idea why.
At my other routes it does work.
I hope you can give me a hint.
Thanks in advance.

Okay I got it to work. It was a fault at my point (as expected). A colleague of mine created a cnontroller in an other path with the same identifier.
So angular doesn't throw an error if something like this happened. Because the second controller was in a lower path it came at the include after the original controller.
Thanks to #MMhunter who put a console output at the constructor. This wasn't printed in my dev environment. So I started to search why, and found the second controller.
Thanks to all of you for your help.

try using just searchUser(query) it might work because controller is already added no need to call the function using controller

Related

AngularJS ui-router - view disappears on reload

Recently I started to use ui-router to manage my page status.
I noticed that when I run the server for the first time, the content is there but if I navigate through the pages or reload the page the contents disappears.
I'm aware there was a bug on ui-router that could be causing this. I updated ui-router however the error still persists.
Did anyone manage to find a fix or work around it?
Edit ----
My investigation has lead me to believe that it has nothing to do with the ui-router and more on the time the app takes to complete the promise. As I will get Violation warnings on the setTimeout as part of jQuery
So I was partially right on my last edit hence this answer; jQuery had something to do with my problem (through the use of promises to retrieve data), however it had also to do with how the ui-router works:
As the page content is loaded, ui-router will manage the first load (and subsequent reloads) with the data that is provided by the GET request.
As this is a promise it is not guaranteed (especially as you grow your DB) that the data will be there in time to render the page.
To avoid from happening use the resolve property as part of ngRoute. This property allows for all the necessary data to be loaded before rendering the DOM.
If you want to read more about follow the link below:
https://medium.com/opinionated-angularjs/advanced-routing-and-resolves-a2fcbf874a1c
My code below:
App.js
'use strict';
angular
.module('knoweeApp', ['ui.router'])
.config(['$stateProvider','$urlRouterProvider',function($stateProvider,$urlRouterProvider) {
$stateProvider
.state('home', {
url:'/',
templateUrl: 'views/user.html',
controller: 'UserCtrl as user',
resolve: {
user: function(userFinder) {
return userFinder.getUsers();
}
}
})
.state('teacher', {
url:'/teacher/:name',
templateUrl: 'views/teacher.html',
controller: 'TeacherCtrl as teacher'
});
$urlRouterProvider.otherwise('/');
}]);
Service: userFinder
'use strict';
/**
* #ngdoc service
* #name knoweeApp.userFinder
* #description
* # userFinder
* Service in the knoweeApp.
*/
angular.module('knoweeApp')
.service('userFinder', function () {
// AngularJS will instantiate a singleton by calling "new" on this function
this.getUsers = function (){
return $.get('users.json');
};
});
Controller: UserCtrl
'use strict';
angular.module('knoweeApp')
.controller('UserCtrl', function (userFinder,user) {
this.teachers = user;
this.increment = function (item) {
item.rating += 1;
};
this.decrement = function (item) {
item.rating -= 1;
};
});
Hope this helps, contact me if in doubt

Why am I able to assign a variable to $rootScope in an Angular controller and access it in the template, but not if I assign the variable to $scope?

I am using the Angular UI Router as my router. I have a $state defined as such:
$stateProvider.state('mypage', {
url:'/',
views: {
'content': {
templateUrl: 'folder/mypage.template.html',
controller: 'MyPageController'
}
}
})
I can go to MyPageController and do the following:
$rootScope.test = "hello!";
And then go to folder/mypage.template.html and put the following:
<div id="example">
{{test}}
</div>
hello! will show up in the rendered web page. However, if I instead do the following in MyPageController:
$scope.test = "hello!";
Nothing will show up in the template. This is very confusing to me, as I know that MyPageController is made available to the state (as I can add something to $rootScope and display it), but the $scope is not available. Does anyone have an idea as to what might be going on? Thank you :)
EDIT1:
MyPageController is part of a module, let's say myModule, that is imported into a top-level module. For example, it looks something like this:
angular.module('topLevelModule', [
'myModule'
]).config( ... $stateProvider stuff ... ).run( ... setup stuff ... )
angular.module('myModule')
.controller('MyPageController', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.test = "hello!";
}]);
EDIT2 (problem solved):
I had followed a tutorial that used the following pattern with multiple states in the UI-Router:
$stateProvider
.state('mainpage', {
url: '/',
views: {
'content': {
templateUrl: 'folder/mainpage.template.html',
controller: 'MainPageController' <-- POINT OF INTEREST 1
}
}
})
.state('mypage', {
url: 'my-page',
controller: 'MyPageController', <-- POINT OF INTEREST 2
views: {
'content#': {
templateUrl: 'folder/mypage.template.html',
<-- POINT OF INTEREST 3
}
}
})
}])
However, the problem lies in this formatting. This is just a heads up for anyone using the UI-Router who happened to follow the same tutorial as I did (I can't find the link), that POINT OF INTEREST 2 needs to be moved to POINT OF INTEREST 3 for the controller to properly be assigned upon state change -- syntax error. There were more complexities to why things were happening (due to my debugging approach) that were causing any inconsistencies you see above, but I won't include them here. Thanks everyone for their time. :)
var test = angular.module('test', []);
test.run(function() {
});
test.config(function() {
// your state for binding html with controller
});
test.controller('MyPageController ', function($scope) {
$scope.test = "hello!";
});
And then in HTML
<div id="example">
{{test}}
</div>

Why doesn't $location.path fire the $routeProvider function?

I'm trying to build my first AngularJS single page application. I copied part of the code below and modified it some. I have a menu bar which calls the Navigate method that I added to the mainController.
When I click on the menu button the expected alert message appears in Navigate, but the alert message in the $routeProvider function only fires when the application starts and it never fires again. I can't find a good explanation of this, but logic says the $routeProvider function should fire when a new $location.path is set in Navigate. Is that wrong? How is this supposed to wire up? Is my nested single page controller causing the menu command to fail?
Also, are there really supposed to be two semicolons at the end or should one of them come after the app.config section?
var app = angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider)
{
alert("$routeProvider " + $routeProvider.path);
$routeProvider
.when('/', {
templateUrl: 'App/Views/Home.html',
controller: 'homeController'
})
.when('/about', {
templateUrl: 'App/Views/About.html',
controller: 'aboutController'
})
.otherwise({
redirectTo: '/'
});
}])
app.controller('mainController', function ($scope)
{
$scope.Title = "Default Title";
$scope.Message = "Default Message";
$scope.Navigate = function (myPath)
{
alert("Navigate " + myPath);
$location.path(myPath);
};
});;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul class="MenuBar">
<li class="MenuButton FloatLeft" ng-click="Navigate('/home');">Home</li>
<li class="MenuButton FloatLeft" ng-click="Navigate('/about');">About</li>
<li class="MenuButton FloatLeft" ng-click="Navigate('/about');">Log In</li>
</ul>
You're trying to run an alert whenever the $routeProvider function runs but it doesn't quite work that way. The $routeProvider function just tells Angular "Whenever the location path changes, refer to this JSON object to know what to do next." Then your code providers some JSON attributes to Angular such as templateUrl and controller. Your alert function will only run once because the $routeProvider is just setup code to configure Angular's routes.
To run code after going to another "page", just add the code to the controller.
Code Example:
app.controller('homeController', function($scope, $http) {
alert("I'm running the homeController() function now");
});
Also, I noticed that you didn't inject $location into your controller. Without this, $location will just be an undefined object. Change your controller definition like this:
app.controller('mainController', function ($scope, $location)
{
$scope.Title = "Default Title";
$scope.Message = "Default Message";
$scope.Navigate = function (myPath)
{
alert("Navigate " + myPath);
$location.path(myPath);
};
});
Remember that any Angular object starting with the $ dollar sign ($timeout, $http, $routeProvider, etc) must be injected into your controller.
You have a few issues with the code you're showing. Not enough details to know for sure but here's what's wrong.
First:
A module's config block will only be executed once, at the start. You're not seeing the alert within your config beyond once because it's only ever called once during the bootstrap of your module.
Second:
You need to inject services that your controller depends on.
app.controller('mainController', function ($scope) { });
Note that you're missing the $location service here.
app.controller('mainController', function ($scope, $location) { });
Third:
We can't see some missing pieces to your code to help you out. You're not showing us how mainController is actually hooked up to anything. How myPath is being sent to the Navigation function on your controller, etc.
I found a nested controller that I wasn't using. When I took that out part of the menu worked. I say part because on some links instead of calling the Navigate function I was setting the window.location. That seems to fire the $routeProvider and the view changes like it should. When I change the Navigate function as shown below it works. I think setting $location.path() in the Navigate function should do the same thing, but it's not working for me.
$scope.Navigate = function (myPath)
{
alert("Navigate " + myPath);
//$location.path(myPath);
window.location = '#' + myPath;
};

why the application not display the first view in angular js

I am trying to display my first view on screen .I used all concept of angular .But it not display or load my template .I didn't get any error .but it not load on html why here is my code
http://goo.gl/VbBnqg
(function() {
'use strict';
angular.module('app.auth').config(Routes);
Routes.$inject = ['$stateProvider', '$urlRouterProvider'];
function Routes($stateProvider, $urlRouterProvider) {
console.log("config call")
// Default
$urlRouterProvider.otherwise('signin');
// Application
$stateProvider
.state('signin', {
url: '/sign-in',
templateUrl: 'js/auth/template/login.html',
controller: 'authenticationCntrl'
})
}
})();
actually my login.html not load why ? why it is not loaded..
here is my project
https://dl.dropbox.com/s/x8s0xbllm270rq5/firstfroject.zip?dl=0
I'll explain the situation a bit more in answer.
According do docs (otherwise() section): https://github.com/angular-ui/ui-router/wiki/URL-Routing
You can pass string (url path) or function to otherwise(). If you would like to use state, you should pass a function that will invoke that state like this:
$urlRouterProvider.otherwise(function($injector, $location){
$injector.invoke(['$state', function($state) {
$state.go('stateName'); //in you case 'signup'
}]);
It will invoke state service and go to 'signup', which has route configured to '/sign-up'. Overall effect will be the same.

Angular best way to handle email confirm route

I'm trying to work out the best way to define a route that users will click on in the confirmation email that they receive.
I have defined a path like this.
app.config(function ($routeProvider, $locationProvider, $httpProvider) {
$routeProvider.when('/app/setup/confirm/:code',{
// code is $routeParams.code
});
});
What needs to happen is:
Make a $http call to the api resource that logs the code as being
clicked and confirms email address
Log the user in for both the api and front end
Return the user to the next step of the setup process now their email is confirmed.
If the code is bogus and the $http call returns false then redirect them to the signup page.
As this route doesn't need a template, I can't work out where to put the code to do this. If I only defined a controller it never gets instantiated until I also define a template??
For example this works
app.config(function ($routeProvider, $locationProvider, $httpProvider) {
$routeProvider.when('/app/setup/confirm/:code',{
controller: function($routeParams){
console.log($routeParams.code);
},
template: function(){
return '<html></html>';
}
});
});
But as soon as I remove the template or even return an empty string in the template the controller doesn't work. There must be right way to do this and this doesn't feel like it.
Can anyone give me a pointer? I'm using v1.1.2. Thanks!
You should be able to resolve the request to a controller without specifying the template. Try this pattern:
app.factory('myService', function () {
return 1;
});
app.controller('MyCtrl', function ($scope, myService) {
console.log(myService);
});
app.config(function ($routeProvider) {
$routeProvider.when('/app/setup/confirm/:code', {
resolve: {
redirect: 'MainCtrl'
}
});
})

Resources