I am not sure what is going wrong in the following code - but it doesn't seems working. can anyone help?
<body ng-controller="MyFunction">
<script>
function MyFunction($scope) {
$scope.author = {
'name':'Test',
'title': 'Mr',
'Job': 'SDE'
}
}
</script>
<h2> {{author.name}} </h2>
<h2> {{author.title + " " + author.Job}} </h2>
</body>
Here you are. You are incorrect in structure of angularjs, I don't see the ng-app and wrong to declare controller:
angular.module('app', []).controller('MyFunction', function($scope) {
$scope.author = {
'name': 'Test',
'title': 'Mr',
'Job': 'SDE'
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app='app' ng-controller="MyFunction">
<h2> {{author.name}} </h2>
<h2> {{author.title + " " + author.Job}} </h2>
</body>
Hope this helps.
There is several things wrong with your code. You are missing an ng-app declaration, you are missing a module to use for that declaration and you did not register your controller correctly. Your example in a working state:
function authorInfoController() {
this.author = {
name: 'Amadeus Smith',
title: 'Prof.',
job: 'Super Senior Cloud Advisor Managment Consultant'
};
}
angular.module("myApp", [])
.controller("AuthorInfoCtrl", authorInfoController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<div ng-app="myApp" ng-controller="AuthorInfoCtrl as info">
<h2>{{info.author.name}}</h2>
<h2>{{info.author.title + " " + info.author.job}}</h2>
</div>
If you are just learning angular, I recommend doing a good tutorial and reading a styleguide.
Related
Here is my custom directive code
(function () {
var app = angular.module('CustDirMod', []);
var custdirCtrl = function ($scope) {
$scope.Person = {
Name: 'Jagan868',
address: {
street: '10 Donwstreet',
city: 'North Avenue',
state: 'Los Angeles'
},
friends: [
'Friend1',
'Friend2',
'Friend3'
]
};
};
var custDirectivewithBinding = function () {
return {
templateUrl: "Friends.html",
restrict: "E",
controller: function ($scope) {
$scope.KnightMe = function (Person) {
Person.rank = "Knight";
}
}
}
};
app.controller('CustDirCtrl', custdirCtrl);
app.directive("custDirectiveBinding", custDirectivewithBinding);
})();
and here is my template html
<div class="panel panel-primary">
<div class="panel-heading">
{{ Person.Name }}
</div>
<div class="panel-body">
<div ng-show='!!Person.address'>
<h4>Address :
</h4>
{{Person.address.street}}
<br />
{{Person.address.city}}
<br />
{{Person.address.state}}
</div>
<h4>Friends :</h4>
<br />
<ul>
<li ng-repeat='friend in Person.friends'>
{{friend}}
</li>
</ul>
<div ng-show="!!Person.rank">
Rank : {{Person.rank}}
</div>
<button ng-show="!Person.rank" class="btn btn-success" ng-click="KnightMe(Person)">Knight Me</button>
</div>
</div>
Now the following final html page where i'm using the above custom directive
<!DOCTYPE html>
<html ng-app="CustDirMod">
<head>
<title>Simple Directives - Angularjs</title>
<script src="Scripts/jquery-3.1.1.js"></script>
<link href="Content/bootstrap.css" rel="stylesheet" />
<script src="Scripts/bootstrap.js"></script>
<script src="Scripts/angular-1.5.8.js"></script>
<script src="Scripts/CustomDirective.js"></script>
</head>
<body ng-controller="CustDirCtrl" class="container" style="padding-top:30px;">
<cust-directive-binding></cust-directive-binding><br /><br />
</body>
</html>
Now i tried to add isolated scope in my custom directive as follows
var custDirectivewithBinding = function () {
return {
templateUrl : "Friends.html",
restrict: "E",
scope: {
userdata: "="
},
controller: function($scope){
$scope.KnightMe = function (Person) {
Person.rank = "Knight";
}
}
}
};
and then in the html page as follows
<body ng-controller="CustDirCtrl" class="container" style="padding-top:30px;">
<cust-directive-binding userdata="Person"></cust-directive-binding><br /><br />
</body>
After adding the isolated scope named as 'userdata' i'm not getting any data in UI. But if i remove that 'userdata' isolated scope from both js & html file its working fine. How to resolve this issue.
P.S: I don't want name the isolated scope local property name same as "Person". I just want it to be something different so that i can distinguish easily.
You don't have a scope property Person in the directive , you renamed it to userdata when you created the isolated scope.
You either need to change the template to now use userdata instead of Person or change the name of userdata to Person so the template will work
scope: {
userdata: "="
}
// in view
{{ userdata.Name}}
Or
<cust-directive-binding Person="Person">
scope: {
Person: "="
}
// in view
{{ Person.Name}}
Because now inside your directive template data will be available with isolated scope variable userdata. To fix the issue you could use userdata instead of Person every where on template. But instead of doing that I'd suggest you to use alias on isolated scope like Person: "=userdata". Where it says userdata will be attribute inside directive data will be available with Person name.
scope: {
Person: "=userdata"
},
I want to write treeview using angularjs. I am using ng-include for recursive call..everything is fine except from ng-click..when each node is clicked..the hierarchy call is from child to it's parents and for every node in this hierarchy the ng-click fires. how can i solve this problem??..I have this exact problem using another approach (appending element on post-link which I think is not a good way) instead of ng-include.here is my code:
index.html:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.0/angular.min.js"></script>
</head>
<body >
<div ng-app="app" ng-controller='AppCtrl'>
<ul>
<li ng-repeat="category in categories" ng-click='nodeSelected(category)' ng-include="'template.html'"></li>
</ul>
</div>
<script src="controller.js"></script>
</body>
</html>
template.html:
{{ category.title }}
<ul ng-if="category.categories">
<li ng-repeat="category in category.categories" ng-click='nodeSelected(category)' ng-include="'template.html'">{{ category.title }}</li>
</ul>
controller.js
var app = angular.module('app', []);
app.controller('AppCtrl', function ($scope) {
$scope.nodeSelected = function(category){
alert('This node is selected' + category.title);
}
$scope.categories = [
{
title: 'Computers',
categories: [
{
title: 'Laptops',
categories: [
{
title: 'Ultrabooks'
},
{
title: 'Macbooks',
categories:[
{
title:'Paridokht'
},
{
title:'Shahnaz',
categories:[
{
title:'Sohrab'
}
]
}
]
}
]
},
{
title: 'Desktops'
},
{
title: 'Tablets',
categories: [
{
title: 'Apple'
},
{
title: 'Android'
}
]
}
]
},
{
title: 'Printers'
}
];
});
here is the output picture:
for example when paridokht node is selected, the alert hierarchy in order is paridokht,macbooks,laptops,computers (from child to parents). please help me to solve this issue. it's killing me! :(
Try stopping event from bubble-ing up in the DOM tree.
In you ng-click:
ng-click='nodeSelected($event, category)'
In your controller:
$scope.nodeSelected = function($event, category){
$event.stopPropagation();
alert('This node is selected' + category.title);
}
I am learning AngularJS from codeSchool and I was making a simple hello world app , initially it was being rendered properly but after some time It didn't work at all. I am not able to detect the bug , please help
Here is the code for html file
<!DOCTYPE html>
<html ng-app="store">
<head>
<title>Angular Code School</title>
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<body>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="app.js"></script>
I am {{4+6}}
{{"Hello +"World"}}
<div ng-controller="StoreCtrl as store">
<div ng-repeat="product in store.products| orderBy:'-price'">
<h2>Name :{{product.name}} </h2>
<h2>Price:{{product.price | currency}} </h2>
<h2>Description:{{product.description}} </h2>
<button ng-show="product.canPurchase">Add To Cart </button>
<section ng-controller="PanelCtrl as panel">
<ul class="nav nav-pills">
<li ng-class="{'active':panel.isSelectedTab(1)}"><a href ng-click="panel.selectTab(1)"> Description</a></li>
<li ng-class="{'active':panel.isSelectedTab(2)}"><a href ng-click="panel.selectTab(2)">Specs</a></li>
<li ng-class="{'active':panel.isSelectedTab(3)}"><a href ng-click="panel.selectTab(3)">Reviews</a></li>
</ul>
<div ng-show="panel.isSelectedTab(1)">This is description div</div>
<div ng-show="panel.isSelectedTab(2)">This is Specification Section</div>
<div ng-show="panel.isSelectedTab(3)">This is Reviews section</div>
</section>
</div>
</div>
</body>
</html>
appTest.js
var app = angular.module('store', []);
app.controller('StoreCtrl', ['$scope', function ($scope) {
this.products = gems;
}])
gems = [{
name: 'Dodecahedron',
price: 2.95,
description: 'This is the description of Dodecahedron'
canPurchase: false;
},
{
name:'Diamond',
price: 5.95,
description: 'Diamond is the most luxuriest gem of all.'
canPurchase:true;
}]
app.controller('PanelCtrl', ['$scope', function ($scope) {
this.tab=1;
this.selectTab = function(setTab) {
this.tab = setTab;
};
this.isSelectedTab = function(checkTab){
return this.tab===checkTab;
}
}])
The structure of my directory is like
root/
angular.js
appTest.js
index.html
Here is the page with console
appTest.js
var app = angular.module('store', []);
app.controller('StoreCtrl', function() {
this.products = gems;
});
app.controller('PanelCtrl', function() {
this.tab = 1;
this.selectTab = function(setTab) {
this.tab = setTab;
};
this.isSelected = function(checkTab) {
return this.tab === checkTab;
};
});
var gems =
[{
name: 'Dodecahedron',
price: 2.95,
description: 'This is the description of Dodecahedron',
canPurchase: false
},
{
name: 'Diamond',
price: 5.95,
description: 'Diamond is the most luxuriest gem of all.',
canPurchase: false
}];
and in index.html
{{"Hello" +"World"}} should be {{"Hello" + "World"}}
You're messing a double quote:
{{"Hello +"World"}}
should be:
{{"Hello " + "World"}}
Check your console for javascript error.
Three issues:
Modify the hello words as below
{{ "Hello" + "World"}}
in your appTest.js,
add the comma after description fields of the 'gem'
remove the ";" semicolon after "canPurchase"
in your html file
ensure you are including "appTest.js" and not just "app.js"
I´m currently starting to learn Angular.JS and worked with a few tutorials like this this one. I followed the Steps but tryed to improve the code by saving single parts like controllers or services in seperate .js files because I heared this is a good habit. That was no problem and all worked fine. But when I came up with the Service which provides my posts I also tried to write some sort of API in the Service because i learned in another tutorial to do so.
There comes the Problem: The API to get my list of posts is working fine but if I try to send data due to an addPost function to the API it doesn´t work at all.
So can you maybe help me to find out what the problem is because I want to implement a Backend to the post-Service later on and want all $http requests at one place.
EDIT
The code-sample below is running now and you can see the problem if you try to add a post. The code stops after/during the addPost() function in the MainCtrl because the "clearing" of the HTML-form isn´t happening.
here you can find my code:
var app = angular.module('flapperNews', []);
app.controller('MainCtrl', function($scope, postService){
$scope.test = "Hello, World!";
$scope.posts = postService.getPosts();
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return; }
postService.addPost({title: $scope.title, link: $scope.link, upvotes: 0});
//This code above was my try ith the API in posts.js
// $scope.posts.push({
// title: $scope.title,
// link: $scope.link, // this whole part is from the tutorial and works fine
// upvotes: 0
//});
$scope.title = '';
$scope.link = '';
};
$scope.incrementUpvotes = function(post) {
post.upvotes += 1;
};
});
app.factory('postService', function() {
var srv = {};
srv._posts = [
{title: 'post 1', link: '', upvotes: 5},
{title: 'post 2', link: '', upvotes: 2},
{title: 'post 3', link: '', upvotes: 15},
{title: 'post 4', link: '', upvotes: 9},
{title: 'post 5', link: '', upvotes: 4}
];
srv.getPosts = function() {
return angular.copy(srv._posts);
};
srv.addPost = function(post) { //function to put the new Post in the Array
srv._posts.push(post);
};
return {
getPosts: function() {
return srv.getPosts();
},
addPost: function(post) { //the public API to put the post in the Array
srv.addPost(post);
}
};
});
<!DOCTYPE html>
<html>
<head>
<meta charset="Utf-8">
<title>FlapperNews</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<style> .glyphicon-thumbs-up { cursor:pointer } </style>
</head>
<body ng-app="flapperNews" ng-controller="MainCtrl">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="page-header">
<h1>Flapper News</h1>
</div>
<div ng-repeat="post in posts | orderBy:'-upvotes'">
<span class="glyphicon glyphicon-thumbs-up"
ng-click="incrementUpvotes(post)"></span>
{{post.upvotes}}
<span style="font-size:20px; margin-left:10px;">
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</span>
</div>
<form ng-submit="addPost()"
style="margin-top:30px;">
<h3>Add a new post</h3>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Title"
ng-model="title"></input>
</div>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Link"
ng-model="link"></input>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
</div>
</div>
<!-- Scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src=scripts/app.js></script>
<script src=scripts/controller/main.js></script>
<script src=scripts/service/posts.js></script>
</body>
</html>
Once you push the data to the service you should update $scope.posts
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return; }
postService.addPost({title: $scope.title, link: scope.link, upvotes: 0});
$scope.posts = postService.getPosts();
// or edit postService.addPost so you can make
/* $scope.posts = postService.addPost({title: $scope.title, link: scope.link, upvotes: 0}); */
$scope.title = '';
$scope.link = '';
};
I am using & (expression binding) operator in isolated scope of a directive but I am unable to trigger function on the parent controller . There should be output on the console but I am receiving none.
Here in the HTML part:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Directive &</title>
<script type="text/javascript" src="angular.min.js"></script>
<script src="isolate_scope_&.js"></script>
</head>
<body ng-app="isolate_scope">
<div ng-controller="isolateScopeController">
<b>Ctrl Data</b>
<div ng-repeat="person in persons">
<p>{{person.name}}</p>
</div>
<b>Directive Data</b>
<div ng-repeat="person in persons">
<friends frnd="person.name"></friends>
</div>
<my-button isolatedFunction="printScopeToFile()"></my-button>
</div>
</body>
</html>
Here goes the JS part :
angular.module('isolate_scope', [])
.controller('isolateScopeController', function($scope){
$scope.persons = [
{
name:"tanmay",
age:"28"
},
{
name: "James",
age:"28"
},
{
name:"Rylan",
age:"26"
},
{
name:"Aditya",
age:"23"
}
];
$scope.printScopeToFile = function(){
console.log("printng to file.....");
for(var i in $scope.persons){
console.log("Name = " + $scope.persons[i].name + " Age = " + $scope.persons[i].age);
}
};
})
.directive('friends',function(){
return {
restrict :'E',
template: '<input type="text" ng-model="name">',
scope :{
name:'=frnd'
}
};
})
.directive('myButton',function(){
return {
restrict: 'E',
template: '<button ng-click="isolatedFunction()">callParentfunction</button>',
scope : {
isolatedFunction:"&"
}
};
});
Fiddle for the same: http://jsfiddle.net/v51kob1q/
The attribute isolatedFunction in your <my-button isolatedFunction...> directive should need to be isolated-function, dash-delimited attributes