AngularJS - routing between views with function doesnt work - angularjs

I have switched to angularJS framework and I have some issues with routing.
This is home.html view
<div id="home">
<label for="priceStart">Kaina nuo:</label><input id="priceStart" type="number" />
<label for="priceEnd">Kaina iki:</label><input id="priceEnd" type="number" />
<input type="button" value="Restoranai" />
<input type="button" value="Maisto tipai" />
<input type="button" ng-click="navigateTo('/mealList');" value="Ieškoti" />
</div>
And this is home.js home controller
FoodSearchControllers.controller('homeCtrl', ['$scope', function($scope) {
navigateTo = function(hash) {
$location.hash(hash);
};
}]);
Can anyone tell me why this doesnt work? Also, it would be good if someone can explain me how to pass variable's from home view to mealList view after this navigateTo() function is called.

If you are using ng-click, Your function in should start with $scope.
FoodSearchControllers.controller('homeCtrl', ['$scope', '$location', function($scope, $location) {
$scope.navigateTo = function(hash) {
$location.hash(hash);
};
}]);

Related

How to assign one controller for Divisions on same page Without $rootScope

My one controller is bind with html by using state file, but i want the same controller work with another page too. But that page has its own controller that's why I include my controller to particular div by using ng-controller attribute. Now my first page is bind properly with controller and the second page is also bind with that same controller but the problem is when I do some changes in first page those changes not reflect back to second page.
How can I achieve this?
Any good Suggestions on how to achieve this?
Here is the PLUNKER DEMO
I want to reflect changes in both when one is changed.
will having a parent controller work for you? Another way to go, which I recommend, is to use a service to share data between controllers
https://plnkr.co/edit/WensNuLiluYcnDyAEIhu?p=preview
<div ng-controller="ParentController">
<div ng-controller="Mycontroller">
<p>Hello {{$parent.name}}!</p>
<label>Name:
<input ng-model="$parent.name" type="text" />
</label>
</div>
<div ng-controller="Mycontroller">
<p>Hello {{$parent.name}}!</p>
<label>Name:
<input ng-model="$parent.name" type="text" />
</label>
</div>
</div>
var app = angular.module('plunker', []);
app.controller('Mycontroller', function($scope) {
});
app.controller('ParentController', function($scope) {
$scope.name = 'World';
});
using service
https://plnkr.co/edit/OWi9LGGkFVorg13kDNaO?p=preview
<div ng-controller="Mycontroller">
<p>Hello {{myService.name}}!</p>
<label>Name:
<input ng-model="myService.name" type="text" />
</label>
</div>
<div ng-controller="Mycontroller">
<p>Hello {{myService.name}}!</p>
<label>Name:
<input ng-model="myService.name" type="text" />
</label>
</div>
var app = angular.module('plunker', []);
app.controller('Mycontroller', function($scope, MyService) {
$scope.myService = MyService;
});
app.service("MyService", function() {
this.name = "World";
});

Why my angular controller don´t find my form - $scope.form undefined

I am trying do understand why my form is not recognize inside the maincontroller, if I put another controller outside, my form is recognize.
config.js
var myApp = angular.module('Myapp', ['ui.router','oc.lazyLoad','ui.bootstrap','kendo.directives','ngStorage',]);
function config($stateProvider, $urlRouterProvider, $ocLazyLoadProvider) {
$urlRouterProvider.otherwise("/index/main");
$stateProvider
.state('testing', {
url: "/testing",
controller: 'MyController',
templateUrl: "testing.html"
});
}
angular
.module('Myapp')
.config(config)
.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
MyController.js
function MyController($scope) {
//do something
$scope.test = {name: 'das'};
$scope.sendTest = function () {
console.log($scope.form.$valid);
console.log($scope.form.testNumber.$valid);
console.log($scope.form.testName.$valid);
};
};
angular
.module('Myapp')
.controller('MyController', ["$scope"]);
testing.html
<form name="form" novalidate>
<p>
<label>Number: </label>
<input type="number" min="0" max="10" ng-model="test.number" name="testNumber" required />
</p>
<p>
<label>Name: </label>
<input type="text" ng-model="test.name" name="testName" required />
</p>
<button ng-click="sendTest()">Submit</button>
</form>
Like this a have this error
TypeError: Cannot read property '$valid' of undefined
but if I create another controller inside MyController.js and i move the code inside like this
function ChildController($scope,$timeout) {
$scope.test = {
name: 'das'
};
$scope.sendTest = function () {
console.log($scope.form.$valid);
console.log($scope.form.testNumber.$valid);
console.log($scope.form.testName.$valid);
};
};
function MyController($scope) { //do other stuff ...};
angular
.module('Myapp')
.controller('ChildController', ["$scope", ChildController])
.controller('MyController', ["$scope"]);
and add the ng-controller to the form like this
<form name="form" novalidate ng-controller='ChildController'>
the form is reconize correctly and working.
Can anyone explain what I am missing here, i would like to understand better, I am a novice.
Thanks you for the help.
Best regards.
Jolynice
As seen in Brad Barber's comment:
The form is being created on the child scope and not the controller
scope.
A good solution like he suggested would be to add the bindToController and controllerAs syntax to your route object:
function config($stateProvider, $urlRouterProvider, $ocLazyLoadProvider) {
$urlRouterProvider.otherwise("/index/main");
$stateProvider
.state('testing', {
url: "/testing",
controller: 'MyController',
controllerAs: 'viewCtrl',
bindToController: 'true',
templateUrl: "testing.html"
});
}
Now you can bind the name of the form as viewCtrl.form:
<form name="viewCtrl.form" novalidate>
<p>
<label>Number: </label>
<input type="number" min="0" max="10" ng-model="viewCtrl.test.number" name="testNumber" required />
</p>
<p>
<label>Name: </label>
<input type="text" ng-model="viewCtrl.test.name" name="testName" required />
</p>
<button ng-click="viewCtrl.sendTest()">Submit</button>
</form>
You can then notate it in your controller using this:
function MyController($scope) {
// Adding variables functions available to ctrl scope
// same as vm = this;
angular.extend(this, {
test: {name: 'das'},
sendTest: function() {
console.log(this.form.$valid);
console.log(this.form.testNumber.$valid);
console.log(this.form.testName.$valid);
}
});
};
angular
.module('Myapp')
.controller('MyController', ["$scope", MyController]);
Here is a codepen that I hacked together for you:
Check whether if the form is inside any div which has ng-if condition
Like
<div ng-if="condition">
<form name="viewCtrl.form">
.
</form>
</div>
If this is so, the form would return undefined since there is new scope created for the DOM containing ng-if condition. Then use ng-show instead of ng-if that would not create new scope. I got this solution from this answer

Not able to access ng-model variables when using ng-view

I have the following Form which I am including in the main app through ng-view
Form Snippet
<form action = "#" method="post" class="form-horizontal" id="commentForm" role="form">
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" type="text" ng-model="userComment" placeholder="New Discussion Topic" rows="5"></textarea>
</div>
</div>
<div class="form-group" id="div_submitComment">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn" type="button" id="submitComment" ng-click="vm.addComment()">Submit comment</button>
</div>
</div>
</form>
Upon clicking the submit button, the controller function will be called. In the controller function, I am not able to access the variable $scope.userComment
Controller Snippet
(function () {
'use strict';
angular
.module('app')
.controller('DiscussionBoardController', DiscussionBoardController);
DiscussionBoardController.$inject = ['UserService', '$rootScope', '$scope', '$cookieStore', 'AuthenticationService'];
function DiscussionBoardController(UserService, $rootScope, $scope, $cookieStore, AuthenticationService) {
function addComment() {
$.getJSON(
"http://localhost/DBoardPage/server/discussion-board/postComment.php", // The server URL
{ userName: $scope.currentUser , userComment:$scope.userComment , commentID:0 }, // Data you want to pass to the server.
$scope.addCommentResponse // The function to call on completion.
);
};
/*End - Discussion Board related Functions*/
}
})();
Though I know that a child scope will be created when we use ng-include, ng-view and ng-repeat, I am not getting an example to explain the usage.
Please let me know how I can get around this preoblem
Are you sure it isn't $scope.currentUser that doesn't exist? You are using a variable that isn't declared.
Try adding:
$scope.currentUser = "";
$scope.userComment = "";
Since you are using AngularJS it might be a better idea creating your function the Angular way.
$scope.addComment = function(){....
If it still doesn't work show more of your setup.

firebaseSimpleLogin: $createUser Promise Not Resolving until Another Event Occurs

I'm setting up registration/login functionality using angular, Firebase, and firebaseSimpleLogin. After reading over a few tutorials and another Stack Overflow thread, I've got the registration working with one small but important caveat: the promise on the SimpleLogin $createUser function isn't resolving until I click on a link or button on my html page. Here's my code:
Register.html
<div class="form-group" >
<label class="control-label" for="email">Email</label>
<input class="form-control" type="text" name="email" id="email" ng-model="cred.email"/>
<label class="control-label" for="password">Password</label>
<div class="form-group">
<input class="form-control" type="password" name="password" id="password" ng-model="cred.password"/>
</div>
<div class="form-group">
<input type="submit" value="Register" class="btn btn-primary" ng-click="register()"/>
</div>
</div>
Main.Js
angular.module('myApp')
.controller('AuthCtrl',
['$scope',
'$location',
'$firebase',
'$firebaseSimpleLogin',
'loginService',
function AuthCtrl($scope, $location, $firebase, $firebaseSimpleLogin,
loginService) {
$scope.register = function(){
var user = {
email: $scope.cred.email,
password: $scope.cred.password
};
loginService.register(user);
};
});
loginService.js (note FBURL is defined elsewhere)
angular.module('myApp')
.factory('loginService', function($firebaseSimpleLogin, $rootScope, $location,
$timeout) {
var ref = new Firebase(FBURL);
var auth = $firebaseSimpleLogin(ref);
return {
register: function (user) {
return auth.$createUser(user.email, user.password)
.then(function(registeredUser) {
console.log(registeredUser);
}
)}
});
In the above loginService.js, I'm not seeing the console.log until I click a button or element; however, the user is created in the Firebase Simple Login DB when I look online. As soon as I click a button or element, the console.log shows. My guess as to the issue is that the promise from auth.$createUser() isn't getting resolved, but I cannot find out why that would be.

template is not updated when model change in Angularjs

I do not know why when I click on Submit button $scope.result get the value (printed out by console.log) but it do not print out any thing by {{result}} in the template while {{countDown}} is still work ok. How to fix it?, thanks
SCRIPT:
angular.module('mean.system').controller('HeaderController', ['$scope', 'Global', $timeout', '$http', '$location', function ($scope, Global, $timeout, $http, $location) {
$scope.findFriend = function() {
$scope.result = "submit button is clicked";
console.log($scope.result); //submit button is clicked
}
$scope.countDown = 10;
var timer = setInterval(function(){
$scope.countDown--;
$scope.$apply();
}, 1000);
}]);
HTML:
<div data-ng-controller="HeaderController">
<div> {{countDown}} </div>
<form ng-submit="findFriend()">
<input type="email" ng-model="friendEmail">
<input type="submit" value="Find">
</form>
</div>
<section data-ng-controller="HeaderController">
<div> Confirm: {{result}} </div>
<div> {{countDown}} </div>
</section>
Here's your problem, other then the previous comment that you were using two controllers, but also, by having your outside of your initial that has the controller on it, then that's outside of the scope.
What you want to do is put the inside the . Here's how it should look along with a fiddle that shows this working for you.
<div ng-controller="MyCtrl">
<div>{{countDown}}</div>
<form ng-submit="findFriend()">
<input type="text" ng-model="friendEmail" />
<input type="submit" value="Find" />
</form>
<div>Confirm: {{result}}</div>
<div>{{countDown}}</div>
</div>
http://jsfiddle.net/HB7LU/1792/
And to be detail oriented, make sure to self close your tags, it's better formed HTML.
To be able to pass variables between different controllers, you can do it using a service as mentioned in the comment, this is a good simple example:
https://gist.github.com/exclsr/3595424
Cheers.

Resources