How to config view and contoller module in angular JS - javascript

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

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

Adding HTML-code for every click with ng-click

I am struggling to understand how to implement an add-function that adds a bit of HTML-code each time I click on a plus-button. The user should be able to add how many questions he/she wants, which means each time you click the button, the new code should be added underneath the previous one. Also I want the input to be added to an array in vm.createdset.question. This is the code I want to add each time I click on a button:
<div class="form-group row question-margin">
<label for="description" class="col-md-2 col-form-label">Fråga 1</label>
<div class="col-md-10">
<textarea type="text" class="form-control" placeholder="Beskriv scenariot och frågan" name="createdset" id="createdset" ng-model="vm.createdset.question.text"></textarea>
</div>
</div>
The button-code:
<i class="fa fa-plus-circle fa-3x new" aria-hidden="true"></i>
You can do this using ng-repeat and an array. All HTML within the div containing the ng-repeat will be repeated for every item in your array.
If you want to keep track of the number of the question you could add newQuestion.id = questionList.length to $scope.addQuestion and instead of using {{$index + 1}} you'll use {{question.id}} instead.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.questionList = [];
$scope.addQuestion = function() {
var newQuestion = {};
newQuestion.content = "";
$scope.questionList.push(newQuestion);
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="addQuestion()">Add Question</button>
<hr />
<div ng-repeat="question in questionList track by $index">
<div class="form-group row question-margin">
<label for="description" class="col-md-2 col-form-label">Fråga {{$index + 1}}</label>
<div class="col-md-10">
<textarea type="text" class="form-control" placeholder="Beskriv scenariot och frågan" name="createdset" id="createdset" ng-model="question.content"></textarea>
</div>
</div>
<hr />
</div>
</div>
</body>
</html>
According to your comments, this should be what you're looking for in your particular case:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, adminService) {
var vm = this;
vm.questionList = [];
vm.addQuestion = function() {
var newQuestion = {};
newQuestion.content = "";
vm.questionList.push(newQuestion);
};
vm.save = function() {
adminService.create(vm.questionList);
};
});
app.service('adminService', function() {
var create = function(answers) {
//Handle your answers and send the result to your webserver.
console.log(answers);
}
return {
create: create
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl as controller">
<button ng-click="controller.addQuestion()">Add Question</button>
<hr />
<div ng-repeat="question in controller.questionList track by $index">
<div class="form-group row question-margin">
<label for="description" class="col-md-2 col-form-label">Fråga {{$index + 1}}</label>
<div class="col-md-10">
<textarea type="text" class="form-control" placeholder="Beskriv scenariot och frågan" name="createdset" id="createdset" ng-model="question.content"></textarea>
</div>
</div>
<hr />
</div>
<div>
<button ng-click="controller.save()">Save</button>
</div>
</div>
</body>
</html>

How to reset input field and checkbox in angularjs

I have a form with single input and another two checkbox labeled with Yes and No.
I want to save the input value when i click yes [this is not the problem].
After clicking yes, input and checkbox should reset. How can i do that?
setting ng-model to null is not working for me.
var app = angular.module("app", ['ionic']);
app.controller("MainCtrl", function ($scope,$timeout,$state) {
$scope.selected='other';
$scope.refresh = function(selected,answer){
if(selected == 'yes'){
$timeout(function(){
$scope.$apply(function(){
$scope.uncheck = false;
})
},250);
}
}
});
<html>
<head>
<link rel="stylesheet" href="http://code.ionicframework.com/1.3.2/css/ionic.css" />
<script src="http://code.ionicframework.com/1.3.2/js/ionic.bundle.min.js"></script>
</head>
<body>
<div class="bar bar-header bar-assertive">
<h1 class="title">Example</h1>
</div>
<div ng-app="app" style="margin-top:64px;padding:20px;">
<div ng-controller="MainCtrl" class="has-header">
<label class="item item-input">
<textarea msd-elastic ng-model="answer.three" placeholder="Your answer"></textarea>
</label>
<div>
<ion-checkbox class="cs-checkbox" ng-model="selected" ng-true-value="'no'" ng-change="statethree(selected,answer)">No</ion-checkbox>
<ion-checkbox class="cs-checkbox" ng-disabled="!answer.three" ng-checked="uncheck" ng-model="selected" ng-true-value="'yes'" ng-change="refresh(selected,answer)">Yes</ion-checkbox>
</div>
</div>
</div>
</body>
</html>
Below is working code with checkboxes but generally in such case it'd be better to use radio buttons (but it would chnage your UI design)
var app = angular.module("app", ['ionic']);
app.controller("MainCtrl", function ($scope,$timeout,$state) {
$scope.selected='other';
$scope.refresh = function(selected,answer){
if($scope.selected){
$timeout(function() {
$scope.answer.three = '';
$scope.selected = '';
}, 250)
};
}
});
<html>
<head>
<link rel="stylesheet" href="http://code.ionicframework.com/1.3.2/css/ionic.css" />
<script src="http://code.ionicframework.com/1.3.2/js/ionic.bundle.min.js"></script>
</head>
<body>
<div class="bar bar-header bar-assertive">
<h1 class="title">Example</h1>
</div>
<div ng-app="app" style="margin-top:64px;padding:20px;">
<div ng-controller="MainCtrl" class="has-header">
<label class="item item-input">
<textarea msd-elastic ng-model="answer.three" placeholder="Your answer"></textarea>
</label>
<div>
<ion-checkbox class="cs-checkbox" ng-true-value="false" ng-model="selected">No</ion-checkbox>
<ion-checkbox class="cs-checkbox" ng-disabled="!answer.three" ng-model="selected" ng-change="refresh(selected,answer)">Yes</ion-checkbox>
</div>
</div>
</div>
</body>
</html>
Also please note that you shouldn't use $apply inside $timeout callback because $timeout already triggers angular digest cycle.

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

Routing issues in Angular

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.

Categories

Resources