Routing issues in Angular - javascript

I'm pretty new to Angular and I came across an issue I can't get around. I did see other people asking the same question, however their problem had to do with a missing ['ngRoute'] .I checked the code many times,but I might have missed something so I'm really hoping I can get some help on this one. Thanks in advance !
directories http://i.stack.imgur.com/zvaqU.png
firstpage.html :
<html ng-app="myApp">
<head>
</head>
<body>
<div ng-view></div>
<script
src="angular.min.js">
</script>
<script
src="angular-route.js">
</script>
<script
src="test.js">
</script>
</body>
</html>
test.js :
var app = angular.module('myApp',['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'SimpleController',
templateUrl: 'Partials/View1.html'
})
.when('/view2',
{
controller: 'SimpleController',
templateUrl: 'Partials/View2.html'
})
.otherwise({redirectTo:'/'});
});
var controllers = {};
controllers.SimpleController = function ($scope) {
$scope.djs=[{name:'Adam Beyer',city:'Sweden',djRank:1},
{name:'Joseph Capriati',city:'Napoli',djRank:4},
{name:'Nina Kraviz',city: 'Moscow',djRank:7},
{name:'Adam Petrov',city:'Sofia',djRank:100}];
$scope.addCustomer() = function () {
$scope.djs.push({name:$scope.newCustomer.name,
city:$scope.newCustomer.city});
};
};
app.controller(controllers);
View1.html :
<div class = "container">
<h2>View 1</h2>
Name:
<br/>
<input ng-model="filter.name" />
<br/>
<ul>
<li ng-repeat="dj in djs|filter:filter.name|orderBy:'djRank'"> {{dj.name}}
</li>
</ul>
<br/>
Customer Name: <br/>
<input type="text" ng-model="customer.name" />
<br/>
Customer City: <br/>
<input type="text" ng-model = "customer.city" />
<br/>
<button ng-click="addCustomer()">Add Customer</button>
</div>
View2.html :
<div class="container">
<h2>View 2</h2>
City:
<br/>
<input type = "text" ng-model="city" />
<br/>
<ul>
<li ng-repeat= "dj in djs |filter:city"</li>
</ul>
</div>

You made a typo in your controller. It should be
$scope.addCustomer = function () {
$scope.djs.push({name:$scope.newCustomer.name,
city:$scope.newCustomer.city});
};
not
$scope.addCustomer() = function () {
$scope.djs.push({name:$scope.newCustomer.name,
city:$scope.newCustomer.city});
};
Notice the parentheses right after addCustomer should not be there.

Related

How to use multiple ng-app and add new modal

Here is my todo.js file
//let example = angular.module("example", ["ngStorage"]);
example.controller("ExampleController", function($scope, $localStorage) {
$scope.save = function() {
let testObject = [
{
name:"aaa",
lastName:"bbb"
},
{
name:"ccc",
lastName:"ddd"
}
]
let myVal = $localStorage.myKey;
$localStorage.$reset();
if(!myVal){
console.log("okey");
$localStorage.myKey = testObject;
} else {
myVal.push({
name:"fff",
lastName:"ggg"
})
$localStorage.myKey = myVal;
}
$scope.datas = $localStorage.myKey;
}
$scope.load = function() {
console.log($localStorage.myKey)
}
});*/
var app = angular.module("modalFormApp", ['ui.bootstrap']);
app.controller("modalAccountFormController", function ($scope, $modal, $log) {
$scope.showForm = function () {
$scope.message = "Show Form Button Clicked";
console.log($scope.message);
var modalInstance = $modal.open({
templateUrl: 'modal.html',
controller: ModalInstanceCtrl,
scope: $scope,
resolve: {
userForm: function () {
return $scope.userForm;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
var ModalInstanceCtrl = function ($scope, $modalInstance, userForm) {
$scope.form = {}
$scope.submitForm = function () {
if ($scope.form.userForm.$valid) {
console.log('user form is in scope');
$modalInstance.close('closed');
} else {
console.log('userform is not in scope');
}
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
And here is my index.html file:
<html>
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="../node_modules/angular-1.6.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.10/ngStorage.min.js"></script>
<script src="./todo.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.9.0.js"></script>
</head>
<body>
<!--<div ng-app="example">
<div ng-controller="ExampleController">
<button ng-click="save()">Save</button>
<button ng-click="load()">Load</button>
<br>
<input type='text' ng-model='searchText' placeholder="Search..." />
<ul>
<li ng-repeat="data in datas | filter:searchText">
{{data.name}}
</li>
</ul>
</div>
</div>-->
<div ng-app="modalFormApp">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<!-- PAGE HEADER -->
<div class="page-header">
<h1>AngularJS Form Validation</h1>
</div>
<div ng-controller="modalAccountFormController">
<div class="page-body">
<button class="btn btn-primary" ng-click="showForm()">Create Account</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Lastly here is my modal.html:
<div class="modal-header">
<h3>Create A New Account!</h3>
</div>
<form name="form.userForm" ng-submit="submitForm()" novalidate>
<div class="modal-body">
<!-- NAME -->
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="name" required>
<p ng-show="form.userForm.name.$invalid && !form.userForm.name.$pristine" class="help-block">You name is required.</p>
</div>
<!-- USERNAME -->
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8" required>
<p ng-show="form.userForm.username.$error.minlength" class="help-block">Username is too short.</p>
<p ng-show="form.userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
</div>
<!-- EMAIL -->
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="email" required>
<p ng-show="form.userForm.email.$invalid && !form.userForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-disabled="form.userForm.$invalid">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</form>
I'm trying to open a modal when i click the button. I made comment line the other part which i'm using but it works fine. The second part is for only the modal but it is not working. I even can not open the modal. If there is a basic way to do this can you share with me? I only need to open this modal. I can handle the rest of it.
From the Docs:
There are a few things to keep in mind when using ngApp:
only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead.
For more information, see
AngularJS ng-app Directive API Reference

angularjs 1 manual bootstrap doesnot work

I am new to angularjs.
I tried to create 2 different modules in an single js file and them manually bootstrap one of them to a element. This was suggested in one of the stackoverflow questions. But this doesnot seem to work.
Both of the modules work fine independently.
I am not sure what is going wrong here.
Here's my code :-
myApp.js
var app = angular.module("myApp", []);
var myController = app.controller("ctrl1", function($scope){
"use strict";
$scope.fname = "Bill";
$scope.lname = "Goldberg";
$scope.updatevalue = function () {
$scope.fullname = $scope.fname + $scope.lname;
//$scope.fname = "newName"
};
});
app.directive("w3TestDirective", function() {
"use strict";
return {
template : "<h1>This is my life!</h1>"
};
});
var loginController = angular.module('loginController', []);
loginController.controller('loginCntrl', function ($scope) {
"use strict";
$scope.username="email";
$scope.password="password";
$scope.present = false;
$scope.login = function () {
"use strict";
if ($scope.username == "Amar" & $scope.password == "Amar") {
$scope.present=true;
$scope.loginMessage = "logged in successfully";
} else {
$scope.present=true;
$scope.loginMessage = "Invalid username or password";
}
}
});
angular.bootstrap(document.getElementById("loginDiv"),['loginController']);
Index.html
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<!--script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.js"></script-->
<script src="scripts/services/myApp.js"></script>
<!--script src="scripts/services/login.js"></script-->
<body>
<div id="demoDiv" ng-app="myApp" ng-controller="ctrl1">
<span>Values:</span>
<input type="text" ng-model="fname"/>
<input type="text" ng-model="lname"/>
<button ng-click="updatevalue()">fullname</button>
<br></br>
{{ fullname }}
<br></br>
<w3-test-directive></w3-test-directive>
</div>
<br></br>
<div id="loginDiv" ng-app="loginController" ng-controller="loginCntrl">
<input type="text" ng-model="username"/>
<input type="text" ng-model="password"/>
<button ng-click="login()">submit</button>
<br></br>
<div ng-if="present"> {{ loginMessage }} </div>
</div>
</body>
</html>
This is the completely wrong approach. You CAN have your controllers in more than one module, but you should always have a single module which is the main parent for the app.
Let's Assume myApp is your parent module, and make some changes:
First, move the ng-app to the body element:
<body ng-app="myApp">
<div id="demoDiv" ng-controller="ctrl1">
...
Next, remove ng-app from the loginDiv:
<div id="loginDiv" ng-controller="loginCntrl">
Finally, inject the loginController module into the myApp module:
var app = angular.module("myApp", ['loginController']);
Now, the app will be able to attach both controllers without issue.
http://plnkr.co/edit/rkFY0ASCHaQUTByaHJg3?p=preview
I fixed my issue with the following code :-
var app = angular.module("myApp", ['utilModule','loginModule']);
var myController = app.controller("ctrl1", function($scope){
"use strict";
$scope.fname = "Bill";
$scope.lname = "Goldberg";
$scope.updatevalue = function () {
$scope.fullname = $scope.fname + $scope.lname;
//$scope.fname = "newName"
};
});
app.directive("w3TestDirective", function() {
"use strict";
return {
template : "<h1>This is my life!</h1>"
};
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<!--script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.js"></script-->
<script src="scripts/services/myApp.js"></script>
<script src="scripts/services/util.js"></script>
<script src="scripts/services/login.js"></script>
<body ng-app="myApp">
<div id="demoDiv" ng-controller="ctrl1">
<span>Values:</span>
<input type="text" ng-model="fname"/>
<input type="text" ng-model="lname"/>
<button ng-click="updatevalue()">fullname</button>
<br></br>
{{ fullname }}
<br></br>
<div ng-controller="utilCntrl">
{{ test }}
<testDirective></testDirective>
</div>
<w3-test-directive></w3-test-directive>
</div>
<br></br>
<div id="loginDiv" ng-controller="loginCntrl">
<input type="text" ng-model="username"/>
<input type="text" ng-model="password"/>
<button ng-click="login()">submit</button>
<br></br>
<div ng-if="present"> {{ loginMessage }} </div>
</div>
</body>
</html>
There is only 1 issue, the testDirective tag doesnot print anything on the browser. but that is not a requirement, so I will just ignore this for the time being.
I realize that this is what #Claies has posted. Claies, Thank you very much for your time and effort.
You can't use the ng-app directive and angular.bootstrap function to bootstrap you angular application. You either use ng-app or angular.bootstrap.
If you have two modules "myApp" and "loginController" like you do in your app, you must make "loginController" a dependency of "myApp". "myApp" will be your angular application module that you can add more dependencies, external or custom.
angular.module('myApp', ['loginController', 'ui-router', 'etc'...])

Angularjs - Displaying data using $http get from remote server

i want to send a http get request which is not a problem.
But the problem is i want to disply the data from the server page. Does it has to be a JSON page to display the data from remote server ? or any sort of data can be displayed ? if yes , then how
Thank you
<div class="form" ng-app="myApp" ng-controller="myCtrl">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="callAPI()" /> </p> <!-- 1 -->
<p>
<ul ng-repeat="post in posts">
<li>{{post}}</li>
</ul>
</p>
<div ng-bind="result"></div> <!-- 5 -->
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.callAPI = function() { // 2
//console.log($scope.url); //3
$http.get($scope.url)
.success(function(response) {
$scope.posts = response.data; //4
});
};
});
</script>
</body>
</html>
another version of code
<div class="form" ng-app="myApp" ng-controller="myCtrl">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="callAPI()" /> </p>
<div ng-bind="result"></div> <!-- 5 -->
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.$watch('url', function() {
fetch();
});
function fetch() {
console.log($scope.url);
$http.get($scope.url)
.success(function(response) {
$scope.result = response.data;
});
}
$scope.callAPI= function() {
this.setSelectionRange(0, this.value.length);
}
});
</script>
</body>
</html>
Like the comments says, I believe that angular look at the content Type of the response to parse the data. Have you try added the accept header type?
What is the content type of the response?
var req = {
method: 'GET',
url: 'http://example.com',
headers: {
'Accept': change this to whatever content you want to accept
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
hey i have found my answer of my question ...
there was a mistake in the source code
here is the right one
<div class="form" ng-app="myApp" ng-controller="myCtrl as controller">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="clickButton()" /> </p>
<p>
<ul>
<li ng-repeat="data in result">
{{data}}
</li>
</ul>
</p>
</div>
and
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.clickButton = function() {
console.log($scope.url);
$http.get($scope.url)
.then(function(response) {
$scope.result = response.data;
});
};
});
</script>
:)
if anyone has a similer problem , i hope this answer will help ..
cheers
function functionName(){
$http.get(URL).success(function(response){
$scope.variable = response;
})
}
inside get() put your url, if your url returning any data then it will go to success() function.

How to config view and contoller module in angular JS

how to link module controller and view in angulaaJS . i am trying to linking with below codes i am getting error please help me to find errors in a code .
controller code:
<!DOCTYPE html>
<html >
<head><title>Angular JS Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-view="" ng-app="myApp">
</div>
<script>
var app=angular.module('myApp',[]);
app.config(function ($routeProvider){
$routeProvider
.when('/view1.html',
{
controller:'myCtrl',
templateUrl:'Partials/view1.html'
})
.when('/view2',
{
controller:'myCtrl',
templateUrl:'Partials/view2.html'
})
.otherwise({redirectTo:'/view1'});
});
app.controller('myCtrl',function($scope){
$scope.customers=[
{name:'JohnSmith',city:'Phonenix'}
{name:'devsenny',city:'New York'}
{name:'benny',city:'san Francisco'}];
});
$scope.addCust=function(){
$scope.customers.push(
{
name:$scope.newcustomer.name,
city:$scope.newcustomer.city});
};
});
</script>
</body>
</html>
CODE FOR VIEW 1:
<div class="container">
<h2>View 1</h2>
Name:
<br/>
<input type="text" ng-model="filter.name"/>
<br/>
<ul>
<li ng-repeat="cust in customers">{{cust}}</li>
</ul>
<br/>
Customer Name:<br/>
<input type="text" ng-model="newcustomer.name">
<br/>
Customer city:<br/>
<input type="text" ng-model="newcustomer.city">
<br/>
<buttton ng-click="addCust()">AddCustomer</button>
</div>
CODE FOR VIEW 2:
<div class="container">
<h2>View 2</h2>
Name:
<br/>
<input type="text" ng-model="filter.name"/>
<br/>
<ul>
<li ng-repeat="cust in customers|filter:filter.name">{{cust}}</li>
</ul></div>
You just have to put your function into your controller ...
app.controller('myCtrl',function($scope){
$scope.customers=[
{name:'JohnSmith',city:'Phonenix'}
{name:'devsenny',city:'New York'}
{name:'benny',city:'san Francisco'}];
$scope.addCust=function(){
$scope.customers.push(
{
name:$scope.newcustomer.name,
city:$scope.newcustomer.city
});
};
});
on top of the #Steeve Pitis response, you need to run this in your web/app server not in your browser

Angularjs Cannot read property 'id' of undefined

I am new to angularjs, I'm trying to create a webapp that can access data from server and post the data to the server. But I'm facing issues, what I did in my application, I have created module,service,view and controller in separate files. I'm unable to access and post data to the server. Can anyone help me.
home.js(controller file)
var myapp = angular.module('demo').controller("homeController", function($scope,myService){
var userArray = {
Id:$scope.user.id,
Model:$scope.user.model,
Name:$scope.user.name,
Color:$scope.user.color,
Price: $scope.user.price
};
myService.async().then(function(d){
$scope.hello=d;
});
$scope.push = function(userArray){
myService.saveUser(userArray).then(function(response){
console.log("inserted");
});
}
});
userService.js(service file)
myapp.factory('myService',function($http){
var myService={
async : function(){
var promise= $http.get('http://jsonplaceholder.typicode.com/posts/1').then(function(response){
console.log(response);
return response;
});
return promise;
},
saveUser : function(user){
$http.post('http://jsonplaceholder.typicode.com/posts',user).success(
function(response,status,headers,config){
});
}
};
return myService;
});
restComponent.js(module file)
var myapp=angular
.module('demo',['ui.router'])
.config(function ($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home',{
url:'/home',
templateUrl:'Templates/home.html',
controller:'homeController'
})
.state('about', {
url:'/about',
templateUrl:'Templates/about.html',
controller:'aboutController'
})
.state('contact',{
url:'/contact',
templateUrl:'Templates/contact.html',
controller:'contactController'
});
});
home.html (view file)
<form ng-submit="mod.push();" ng-controller="homeController as mod">
Id:<br>
<input type="text" name="id" ng-model="mod.user.id"><br>
Model:<br>
<input type="text" name="model" ng-model="mod.user.model"><br>
Name:<br>
<input type="text" name="name" ng-model="mod.user.name"><br>
Color:<br>
<input type="text" name="color" ng-model="mod.user.color"><br>
Price:<br>
<input type="text" name="price" ng-model="mod.user.price"><br>
<br>
<input type="submit" >
</form>
<br>
<br>
<table>
<thead>
<th>UserId</th>
<th>Name</th>
<th>Country</th>
</thead>
<tbody>
<tr ng-repeat="employee in hello">
<td>{{employee.userId}}</td>
<td>{{employee.name}}</td>
<td>{{employee.country}}</td>
</tr>
</tbody>
</table>
index.html
<!doctype html>
<html lang="en" >
<head>
<meta charset="utf-8">
<title>RestApi</title>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<script src="bower_components/angular/angular.js"></script>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/angular-ui- router/0.3.1/angular-ui-router.js
"></script>
<script src="rest-controller.component.js"></script>
<script src="Controllers/contact.js"></script>
<script src="Controllers/about.js"></script>
<script src="Controllers/home.js"></script>
<script src="Service/userService.js"></script>
</head>
<body ng-app="demo" >
<ol>
<li><a ui-sref="home">Home</a></li>
<li><a ui-sref="about">About</a></li>
<li><a ui-sref="contact">Contact</a></li>
</ol>
<div ui-view></div>
</body>
</html>
change that
you didnt declare your scope so its undefined that why better to declare it before using it
also removes that user array you did not need for that
var myapp = angular.module('demo').controller("homeController", function($scope,myService){
$scope.user = {}; // here you declare the user obkect
$scope.push = function(user){
myService.saveUser(user).then(function(response){
console.log("inserted");
});
}
})
and home html
you wanted to use scope but you used controller var
the view know the scope and all his objects so just write the var fun name and it will go to it directly
or you can do the same with controller by using this instead of scope and mod like you did
here you should send the user or you can do it in controller by sending the $scope.user
<form ng-submit="push(user);">
Id:<br>
<input type="text" name="id" ng-model="user.id"><br>
Model:<br>
<input type="text" name="model" ng-model="user.model"><br>
Name:<br>
<input type="text" name="name" ng-model="user.name"><br>
Color:<br>
<input type="text" name="color" ng-model="user.color"><br>
Price:<br>
<input type="text" name="price" ng-model="user.price"><br>
<br>
<input type="submit" >
</form>
and route
better to declare the controller on the view but you cant do them both so i chosed the view controller
var myapp=angular
.module('demo',['ui.router'])
.config(function ($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home',{
url:'/home',
templateUrl:'Templates/home.html'
})
.state('about', {
url:'/about',
templateUrl:'Templates/about.html'
})
.state('contact',{
url:'/contact',
templateUrl:'Templates/contact.html'
});
});
should work that way

Categories

Resources