AngularJs' model in dynamic view - javascript

Here is what i am trying to do.
In this app, user can click "Add" to add whatever category they want in this form, and i will save all of them, then output it. However, i could not figure out how to output them.
Here is a working example for the dynamic view:http://plnkr.co/edit/j5RGMi3RTPZ85XGvaa2D?p=preview
Here is the js file:
var app = angular.module('plunker', []);
app.controller('ctrl',['$scope', function($scope){
$scope.templates = [];
$scope.addTemplate = function(){
$scope.templates.push('category');
};
}]);
Here is the view:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js" data-semver="1.0.8"></script>
<script src="app.js"></script>
<p>Append Category via button click</p>
<button ng-click="addTemplate()">Add Category</button>
<div ng-repeat="template in templates">
<ng-include src="template"></ng-include></div>
<script type="text/ng-template" id="category">
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" for="categoryTitle">Title</label>
<div class="col-sm-10">
<input id="categoryTitle" name="categoryTitle" ng-model="category.title" type="text" class="form-control" placeholder="Input your category title" required>
</div>
</div>
<br>
<!-- Begin textarea -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<textarea id = "nonresizable" class="form-control" ng-model="category.content" placeholder="Input your category content here" rows="5" required></textarea>
<hr>
</div>
</div>
<!-- End textarea -->
</form>
<p>The inputed Category</p>
<label>Title</label>
<div>{{category.title}}</div>
<div class="col-sm-offset-2 col-sm-10">
<textarea>{{category.content}}</textarea>
<hr>
</div>
Any thoughts would be much appreciated!

You want to change the content in $scope.templates after you add the a note/page?
If you want to change the content of every note in the template you can:
var app = angular.module('plunker', []);
app.controller('ctrl',['$scope', function($scope){
$scope.templates = [];
$scope.addTemplate = function(){
$scope.templates.push({
content1 : "content1text",
content2 : "content3text",
content3 : "content3text"
});
};

You can make somethinkg like that
just proposition
Templates.js
var tempsObj = {} | tempsObj;
tempsObj.templates = function(){
var template = [];
template ["templates1"] = "folder1/";
template ["templates2"] = "folder1/";
return template;
}
tempsObj.selectedTemp = "templates1";
Module.js
var app = angular.module("plunker",['ngRoute']);
home.config(function($routeProvider,$locationProvider){
$routeProvider
.when('/',{
templateUrl : tempsObj.templates[tempsObj.selectedTemp]+'plunker.html',
controller : 'plunkerController'
})
.when('/404',{
templateUrl : tempsObj.templates[tempsObj.selectedTemp]+'404.html',
controller : '404Controller'
})
.otherwise({
redirectTo : '/404'
});
});

So, I did more research and made it work! YAY!
Here is a live demo in plunker, http://plnkr.co/edit/AQFlEV6FDEKRAsvBc0PE?p=preview.
$scope.addField = function() {
$scope.data.fields.push({
content: "test " + counter++
});
};
Basically I need to dynamic add the name for each category, everytime push the new category to the scope. Hope this makes sense.
Thanks again for all the answers!

Related

AngularJS controller only working on first view

I am having some problems running my first AngularJS app. When I run my app all objects on my index are displayed properly. When I click on my hyperlink to move to view-2 all objects are displayed on HTML like plain text {{object.property}} What am I doing wrong?
This is my index.html:
<DOCTYPE html>
<html ng-app="tutorialApp">
<head>
<meta charset="UTF-8">
<title> Tutorial App</title>
<script src="lib/angular.min.js"></script>
<script src="lib/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/MyController.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
</DOCTYPE>
this is my app.js:
var app = angular.module('tutorialApp', ["ngRoute", "MyControllerModule"])
app.config(function ($routeProvider){
$routeProvider
.when("/", {
controller: "MyController",
templateUrl: "views/one.html"
})
.when("/two", {
controller: "ControllerTwo",
templateUrl: "views/two.html"
})
.otherwise({
redirectTo: "/"
});
});
this is my MyController.js:
angular.module("MyControllerModule", [])
.controller("MyController", ["$scope", function($scope){
$scope.myFirstObject = {};
$scope.myFirstObject.title = "Main Page";
$scope.myFirstObject.subTitle = "Sub Title";
$scope.myFirstObject.bindOutput = 13;
$scope.myFirstObject.firstname = "Wheelchair";
$scope.myFirstObject.lastname = "Terminator";
$scope.timesTwo = function(){
$scope.myFirstObject.bindOutput *= 2;
}
}])
.directive("myFirstDirective", function(){
return {
restrict: "E",
template: "<div>Hello how are you?</div>"
}
})
.controller("ControllerTwo", ["$scope", function($scope) {
$scope.testObject = {};
$scope.testObject.doSomething = "TEST TEST TEST TEST TEST!";
}
]);
This is my /views/one.html:
<h1>{{myFirstObject.title}}</h1>
<h2>{{myFirstObject.subTitle}}</h2>
<p>Number: {{2 + 2}}</p>
<p>String: {{myFirstObject.firstname + " " + myFirstObject.lastname}}</p>
<p><b>Multiply a number by two: {{myFirstObject.bindOutput | currency}}</b></p>
<button ng-click="timesTwo()">CLICK TO MULTIPLY</button><br>
<br>
<label>First Name:</label>
<input ng-model="myFirstObject.firstname">
<br>
<label>Last Name:</label>
<input ng-model="myFirstObject.lastname">
<br>
CLICK HERE FOR SECOND VIEW
<br>
<br>
<br>
<my-first-directive></my-first-directive>
this is my /views/two.html
<h1>Second View</h1>
<h2>this is the second view...</h2>
<br>
<br>
<p>Call object string: {{testObject.doSomething}}</p>
Change the href to route. Not html page.
CLICK HERE FOR SECOND VIEW
This should be
CLICK HERE FOR SECOND VIEW
As you did in the question, that calls the new html page to load into the browser. Not template of angular app. So, all the unknown stuff like {{object.property}} happens.
Use,
CLICK HERE FOR SECOND VIEW
Observe, href="#two"
<h1>{{myFirstObject.title}}</h1>
<h2>{{myFirstObject.subTitle}}</h2>
<p>Number: {{2 + 2}}</p>
<p>String: {{myFirstObject.firstname + " " + myFirstObject.lastname}}</p>
<p><b>Multiply a number by two: {{myFirstObject.bindOutput | currency}}</b></p>
<button ng-click="timesTwo()">CLICK TO MULTIPLY</button><br>
<br>
<label>First Name:</label>
<input ng-model="myFirstObject.firstname">
<br>
<label>Last Name:</label>
<input ng-model="myFirstObject.lastname">
<br>
CLICK HERE FOR SECOND VIEW
<br>
<br>
<br>
<my-first-directive></my-first-directive>
Check this reference
EDIT:
You seems to have issue with # url's
Solution:
HTML5 Mode
Configuration:
$routeProvider
.when('/two', {
templateUrl: 'views/two.html',
});
$locationProvider
.html5Mode(true);
You should set the base in HTML-file
<html>
<head>
<base href="/">
</head>
</html>
In this mode you can use links without the # in HTML files
link
example:
http://test.com/base/two

How to push items into the controller array using a form with input fields and that will show up in the view

INDEX.HTML
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.2/angular.js" data-semver="1.4.2"></script>
<script src="app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.0/ui-bootstrap-tpls.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="module in validation.modules">Title:{{module.title}}
description:{{module.description}}</div>
<div>
<form name="myForm" novalidate class="simple-form">
Title: <input value="" type="text" placeholder="a" ng-model="itemAmount"><br />
description: <input value="" type="text" placeholder="Name of Item" ng-model="itemName">
<br />
<button ng-click="addItem()">Add to list</button>
</form>
</div>
</body>
</html>
APP.JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.validation = {
"modules":
[
{
"title":"name of validation1",
"description":"description of validation1"
},
{
"title":"name of validation2",
"description":"description of validation2"
}
]
};
$scope.addItem = function () {
$scope.validation.modules.push({
title: $scope.itemAmount,
description: $scope.itemName
});
};
});
The below file is a pluknr in which i am just binding using ng-model to display
http://plnkr.co/edit/5NXHQiOApzNU5cn0yQT2
My Question is that you can see in the plunker file that there is a add to list button .. what i want to do is that i want to add a pop up tab like the one you can see in the MODAL section in the below link
https://angular-ui.github.io/bootstrap/
and add some text fields to it let's suppose a form and when i click add to list in the pop up form i want it to be added in the view..
Here you go
http://plnkr.co/edit/nI6PhjbAKEdTgXeWMKDx?p=preview
Opening the modal in main controller and handling the result from modal:
$scope.openModal = function() {
var modalInstance = $modal.open({
templateUrl : 'myModal.html',
controller: 'myModalController'
})
modalInstance.result.then(function(info) {
console.log(info);
$scope.validation.modules.push(info);
})
Binding data into modal controller:
app.controller('myModalController', function($scope, $modalInstance) {
$scope.infoToAdd = {
title: "",
description: ""
}
$scope.addItem = function() {
$modalInstance.close($scope.infoToAdd);
}
$scope.cancel = function() {
$modalInstance.dismiss("cancel");
}
});
Template:
<script type="text/ng-template" id="myModal.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
Title: <input type="text" placeholder="Title" ng-model="infoToAdd.title"><br />
description: <input type="text" placeholder="Description" ng-model="infoToAdd.description">
<br />
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="addItem()">Add to list</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>

Angular : Bootstrap giving error in console

Here is my code :
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script type="text/javascript" src="./angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
var app1 = angular.module('myApp1', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "sparsh";
$scope.lastName = "khandelwal";
});
</script>
<title>Home Page</title>
</head>
<body>
<div ng-app="myApp" ng-init="name='Sparsh'">
<div ng-controller="myCtrl">{{firstName}}</div>
<p>
Name : <input type="text" ng-model="name">
</p>
<h1>Hello {{name}}</h1>
</div>
<div ng-app="myApp1" ng-init="names=['Jani','Hege','Kai']">
<ul>
<li ng-repeat="x in names">{{x}}</li>
</ul>
</div>
<script type="text/javascript">
angular.bootstrap(document, ['myApp1','myApp']);
</script>
</body>
</html>
Although i can see the expected output, but at the same time facing console error.
here is the description of error
(while i click on the url)
it says it already bootstrapped so i remove the 'myApp' from .bootstrap function, but that didnt work.
Please help.
You are doing both ng-app declarations and angular.bootstrap(document, ['myApp1','myApp']);.
You need to choose only one method, otherwise you get the well descripted error of multiple bootstrapped applications.
The problem is as explained in the previous comments, the automatic and manual initialization of modules.
Since you want to initialize them separately for each elements then try an approach like
<div data-app="myApp" ng-init="name='Sparsh'">
<div ng-controller="myCtrl">{{firstName}}</div>
<p>
Name : <input type="text" ng-model="name"/>
</p>
<h1>Hello {{name}}</h1>
</div>
<div data-app="myApp1" ng-init="names=['Jani','Hege','Kai']">
<ul>
<li ng-repeat="x in names">{{x}}</li>
</ul>
</div>
then
var app = angular.module('myApp', []);
var app1 = angular.module('myApp1', []);
app.controller('myCtrl', function ($scope) {
$scope.firstName = "sparsh";
$scope.lastName = "khandelwal";
});
var els = document.querySelectorAll('[data-app]');
for (var i = 0; i < els.length; i++) {
angular.bootstrap(els[i], [els[i].dataset.app]);
}
Demo: Fiddle

Controller not a function got undefined error message angular js

I am a beginner with MEAN Stack development. I was trying out to play around with some angular stuff but got completely messed up the the controllers.
Here is my main html file
<!--main.html-->
<html>
<head>
<title>Chirp</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="javascripts/chirpApp.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body ng-app="chirpApp">
<div id='main' class="container" ng-controller="mainController">
<div class="col-md-offset-2 col-md-8">
<div class="clearfix">
<form ng-Submit="post()">
<input required type="text" class="form-control" placeholder="Your name" ng-model="newPost.created_by" />
<textarea required class="form-control" maxlength="200" rows="3" placeholder="Say something" ng-model="newPost.text"></textarea>
<input class="btn submit-btn pull-right" type="submit" value="Chirp!" />
</form>
<div id="post-stream">
<h4>Chirp Feed</h4>
<div class="post" ng-repeat="post in posts | orderBy:'created_at':true" ng-class-odd="'odd'" ng-class-even="'even'">
<p>{{post.text}}</p>
<small>Posted by #{{post.created_by}}</small>
<small class="pull-right">{{post.created_at | date:"h:mma 'on' MMM d, y"}}</small>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I have created another html file for registration. here is the code for it.
<!--register.html-->
<html>
<head>
<title>Chirp</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="javascripts/chirpApp.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body ng-app="chirpApp">
<div id='main' class="container" ng-controller="authController">
<form class="form-auth" ng-submit="register()">
<h2>Register</h2>
<p class="text-warning">{{error_message}}</p>
<input type="username" ng-model="user.username" placeholder="Username" class="form-control"><br>
<input type="password" ng-model="user.password" placeholder="Password" class="form-control"><br>
<input type="submit" value="Register" class="btn btn-primary" />
</form>
</div>
</body>
</html>
I have created two separate controllers for registration and posts. the first controller works nicely but whenever I am trying to add a second controller I am getting an error message. Here is the code for my controllers.
//chirpApp.js
var app = angular.module('chirpApp', []);
app.controller('mainController', function($scope){
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
});
app.controller('authController', function($scope){
$scope.user = {username: '', password: ''};
$scope.error_message = '';
$scope.login = function(){
//placeholder until authentication is implemented
$scope.error_message = 'login request for ' + $scope.user.username;
};
$scope.register = function(){
//placeholder until authentication is implemented
$scope.error_message = 'registeration request for ' + $scope.user.username;
};
});
I am getting the following error in the chrome console :
Error: [ng:areq] http://errors.angularjs.org/undefined/ng/areq?p0=authController&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:6:453
at tb (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:18:250)
at Oa (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:18:337)
at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:61:288)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:48:476
at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:7:367)
at S (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:48:342)
at h (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:43:59)
at h (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:43:76)
main.html works fine and the data is being binded successfully.
The issue is with the register.html page. I suppose the authController is not getting binded
Can anyone suggest me the best way of implementing the same? And why the controller is getting undefined?
Try the following checklist:
angularjs lib is included in
ng-app=".." directive is in index.html
..path/to/module and other controllers in index.html
module and controllers defined correctly (spelling, syntax etc)
Controller example (if not using global angular var:
app.controller('AppController', ['$http', '$scope', '$log',
function($http, $scope, $log) {
// TODO: implement
}
]);
Hope this helps.
Here is the plunker of your files
http://embed.plnkr.co/6jNXImBddYqjK23FCWUy/preview
Your application works as expected. Please check your core files is loaded or not.
Hope this helps
your code
When you create a new controller with the AngularJS Controller Sub-Generator you have to reboot Grunt.

Argument 'customerCtrl' is not aNaNunction, got undefined

I'm getting a curious error that seems to suggest my controller is not being created properly. Can anyone explain? This is my first SPA app so I'm programming in the dark a little bit.
Here is my master page:
<!DOCTYPE html>
<html ng-app="ibosApp">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>iBOS</title>
<script src="/Scripts/jquery-1.10.2.min.js"></script>
<script src="/Scripts/angular.min.js"></script>
<script src="/Scripts/angular-route.min.js"></script>
<script src="/Scripts/bootstrap-select.js"></script>
<script src="/angular/scripts/route-config.js"></script>
<script src="/Scripts/bootstrap-select.js"></script>
<link href="/Content/bootstrap.min.css" rel="stylesheet" />
<link href="/Content/bootstrap-select.css" rel="stylesheet" />
<link href="/Content/acs.css" rel="stylesheet"/>
<script type="text/javascript">
$(function () {
$('.selectpicker').selectpicker();
});
</script>
</head>
<body>
<div class="container body-content">
<ng-view/>
</div>
</body>
</html>
Here is my view template:
<div class="tab-content">
<div id="customers" class="tab-pane fade active in top-buffer" ng-controller="customerCtrl">
<form class="form-group">
<div class="container">
<div class="row">
<div class="col-sm-3">
<label for="customer-broker">Broker:</label>
<select class="selectpicker" id="customer-broker"></select>
</div>
<div class="col-sm-3">
<label for="customer-town">Town:</label>
<input type="text" class="form-control" id="customer-town"/>
</div>
<div class="col-sm-3">
<label for="customer-code">Code:</label>
<input type="text" class="form-control" id="customer-code"/>
</div>
<div class="col-sm-3">
<button ng-click="search()" class="btn">Search</button>
<button ng-click="myCustomers()" class="btn">My customers</button>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<label for="customer-company-name">Company name:</label>
<input type="text" class="form-control" id="customer-company-name"/>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<label for="customer-contact-name">Contact name:</label>
<input type="text" class="form-control" id="customer-contact-name"/>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<label for="customer-customer-id">Customer ID:</label>
<input type="text" class="form-control" id="customer-customer-id"/>
</div>
</div>
</div>
</form>
</div>
</div>
<script type="text/javascript">
angular.module('ibosApp', ['angular-bootstrap-select', 'ngRoute'])
.controller("customerCtrl", function($scope, $http) {
$scope.loadBrokers = function() {
$http.get("/api/customers/getBrokers").success(function(data) {
$scope.brokers = data;
});
}
$scope.loadBrokers();
}
);
</script>
but I get the error "Argument 'customerCtrl' is not aNaNunction, got undefined" and the controller constructor is never called. Can anyone explain why?
M
EDIT - more code
Here is my route config...
angular.module("ibosApp", ["ngRoute"])
.config(function($routeProvider) {
$routeProvider.otherwise({
templateUrl: "/angular/components/booking-system/booking-system-template.html"
});
});
EDIT - full stack trace of error
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.13/$injector/modulerr?p0=ibosApp&p1=Error%3…20d%20(http%3A%2F%2Flocalhost%3A4685%2FScripts%2Fangular.min.js%3A17%3A381)
There's a few things wrong.
You're setting ibosApp twice, i.e., angular.module("ibosApp", ["ngRoute"]) and angular.module("ibosApp", ['angular-bootstrap-select'])
You should only do this once, with all of your dependencies:
angular.module("ibosApp", ['ngRoute', 'angular-bootstrap-select']);
...and then use the getter syntax, which is the same, without the second parameter:
angular.module('ibosApp')
You can't define controllers in the view like you're doing unless you re-compile your angular app. It would be best to put your javascript into a separate file and include that script on your index page. The reason this isn't working is because your angular app compiles one time, then you load the view and define the controller, but angular doesn't know about that control since it wasn't there when you compiled it.
So:
app.js
angular.module("ibosApp", ["ngRoute", "angular-bootstrap-select"])
.config(function($routeProvider) {
$routeProvider.otherwise({
templateUrl: "/angular/components/booking-system/booking-system-template.html"
});
});
customerCtrl.js
angular.module('ibosApp').controller("customerCtrl", function($scope, $http) {
$scope.loadBrokers = function() {
$http.get("/api/customers/getBrokers").success(function(data) {
$scope.brokers = data;
});
}
$scope.loadBrokers();
}
);
And your markup would be
// previous script tags
<script src="app.js"></script>
<script src="customerCtrl.js"></script>
Is your module only defined in the template? If that's the case that might be your problem, the app isn't initialized since ng-app can't find the module you're trying to load. I would begin with separating JavaScript and HTML to make it easier on yourself.

Categories