Getting error while include multiple controller in Angular js - angularjs

I am new to angular js. I am trying to build a web apps with Angular and Rails from thinkster. I have made a index page on which i had load the home template, home template carries two field i.e title and link of the post and a submit button. On submitting the title and link is added to an array and displays it on the home page. Now i have added another another template that is post, in which their is facility to comment on a particular post but after including the post template and controller my app is not running. Help me in solving the problem.
index.html file contain :
<html>
<head>
<title>Flapper News</title>
<link href="bootstrap.min.css" rel="stylesheet">
<script src="angular.min.js"></script>
<script src="app.js"></script>
<script src="angular-ui-router.js"></script>
<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">
<ui-view> </ui-view>
</div>
</div>
<script type="text/ng-template" id="/posts.html">
<div class="page-header">
<h3>
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</h3>
</div>
<div ng-repeat="comment in post.comments | orderBy:'-upvotes'">
<span class="glyphicon glyphicon-thumbs-up"
ng-click="incrementUpvotes(comment)"></span>
{{comment.upvotes}} - by {{comment.author}}
<span style="font-size:20px; margin-left:10px;">
{{comment.body}}
</span>
</div>
<form ng-submit="addComment()"
style="margin-top:30px;">
<h3>Add a new comment</h3>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Comment"
ng-model="body"></input>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
</script>
<script type="text/ng-template" id="/home.html">
<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>
<span>
Comments
</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>
</script>
</body
app.js contain :
angular.module('flapperNews', ['ui.router'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
});
$stateProvider
.state('posts', {
url: '/posts/{id}',
templateUrl: '/posts.html',
controller: 'PostsCtrl'
});
$urlRouterProvider.otherwise('home');
}])
.factory('posts', [function(){
var o = {
posts: [
{title: 'post 1', link: 'link1',upvotes: 5},
{title: 'post 2', link: 'link2',upvotes: 2},
{title: 'post 3', link: 'link3',upvotes: 15},
{title: 'post 4', link: 'link4',upvotes: 9},
{title: 'post 5', link: 'link5',upvotes: 4}
]
};
return o;
}])
.controller('PostsCtrl', [
'$scope',
'$stateParams',
'posts',
function($scope, $stateParams, posts){
$scope.post = posts.posts[$stateParams.id];
$scope.addComment = function(){
if($scope.body === '') { return; }
$scope.post.comments.push({
body: $scope.body,
author: 'user',
upvotes: 0
});
$scope.body = '';
};
}]);
.controller('MainCtrl', [ '$scope', 'posts',
function($scope, posts){
$scope.posts = posts.posts;
$scope.addPost= function(){
if(!$scope.title || $scope.title === '') { alert("Field can't left blank"); return; }
$scope.posts.push({
title: $scope.title ,
link: $scope.link,
upvotes: 0,
comments: [
{ author: 'Joe', body: 'Cool post!', upvotes: 0 },
{ author: 'Bob', body: 'Great idea but everything is wrong!', upvotes: 0 }
]
});
$scope.title='';
$scope.link='';
};
$scope.incrementUpvotes= function(post){
post.upvotes += 1;
};
}]);
Any idea what i am doing wrong?
`

Try below app.js. I have removed the semicolon.
angular.module('flapperNews', ['ui.router'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
});
$stateProvider
.state('posts', {
url: '/posts/{id}',
templateUrl: '/posts.html',
controller: 'PostsCtrl'
});
$urlRouterProvider.otherwise('home');
}])
.factory('posts', [function(){
var o = {
posts: [
{title: 'post 1', link: 'link1',upvotes: 5},
{title: 'post 2', link: 'link2',upvotes: 2},
{title: 'post 3', link: 'link3',upvotes: 15},
{title: 'post 4', link: 'link4',upvotes: 9},
{title: 'post 5', link: 'link5',upvotes: 4}
]
};
return o;
}])
.controller('PostsCtrl', [
'$scope',
'$stateParams',
'posts',
function($scope, $stateParams, posts){
$scope.post = posts.posts[$stateParams.id];
$scope.addComment = function(){
if($scope.body === '') { return; }
$scope.post.comments.push({
body: $scope.body,
author: 'user',
upvotes: 0
});
$scope.body = '';
};
}])
.controller('MainCtrl', [ '$scope', 'posts',
function($scope, posts){
$scope.posts = posts.posts;
$scope.addPost= function(){
if(!$scope.title || $scope.title === '') { alert("Field can't left blank"); return; }
$scope.posts.push({
title: $scope.title ,
link: $scope.link,
upvotes: 0,
comments: [
{ author: 'Joe', body: 'Cool post!', upvotes: 0 },
{ author: 'Bob', body: 'Great idea but everything is wrong!', upvotes: 0 }
]
});
$scope.title='';
$scope.link='';
};
$scope.incrementUpvotes= function(post){
post.upvotes += 1;
};
}]);

<!DOCTYPE html>
<head>
<title>Angular JS Includes</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body ng-app = "mainApp">
<h2>AngularJS Sample Application</h2>
<div ng-controller = "studentController">
<table>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>
<tr ng-repeat = "student in students">
<td>{{ student.Name }}</td>
<td>{{ student.RollNo }}</td>
<td>{{ student.Percentage }}</td>
</tr>
</table>
</div>
<div ng-controller="employeeController">
<table>
<tr>
<th>EmpName</th>
<th>EmpID</th>
<th>Salary</th>
</tr>
<tr ng-repeat = "employee in employees">
<td>{{ employee.EmpName }}</td>
<td>{{ employee.EmpID }}</td>
<td>{{ employee.Salary }}</td>
</tr>
</table>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope,$http) {
var url = "data.txt";
$http.get(url).success( function(response) {
$scope.students = response;
});
});
mainApp.controller('employeeController', function($scope,$http) {
var url1 = "empdata.txt";
$http.get(url1).success( function(response1) {
$scope.employees = response1;
});
});
</script>
</body>
</html>
<make a file with data like below data.txt>
[
{
"Name" : "Mahesh Parashar",
"RollNo" : 101,
"Percentage" : "80%"
},
{
"Name" : "Dinkar Kad",
"RollNo" : 201,
"Percentage" : "70%"
},
{
"Name" : "Robert",
"RollNo" : 191,
"Percentage" : "75%"
},
{
"Name" : "Julian Joe",
"RollNo" : 111,
"Percentage" : "77%"
}
]
<make a file with data like below empdata.txt>
[
{
"EmpName" : "Mahesh Parashar",
"EmpID" : 101,
"Salary" : "80000"
},
{
"EmpName" : "Dinkar Kad",
"EmpID" : 201,
"Salary" : "70000"
},
{
"EmpName" : "Robert",
"EmpID" : 191,
"Salary" : "75000"
},
{
"EmpName" : "Julian Joe",
"EmpID" : 111,
"Salary" : "77000"
}
]

Related

Filtering on a formatted datefield

I've started recently with AngularJS, and I've come across this problem.
I'm filtering a list with a Angular Filter object. It all works, but I want to be able to type a date value to filter the date column. Problem is, the date that comes from my webservice is (ofcourse) in another format than the showed date.
Here is an example:
View:
Name: <input type="text" ng-model="search.Name"><br>
Date: <input type="text" ng-model="search.Date"><br>
<table>
<tr ng-repeat="item in filtered = (list | filter:search)">
<td>{{item.Name}}</td>
<td>{{item.Date | date:'dd-MM-yyyy'}}</td>
</tr>
</table>
Controller:
app.controller('MainCtrl', function($scope) {
$scope.list = [{
Name: "Item1",
Date: "2018-08-06T13:43:11.82Z"
},{
Name: "Item2",
Date: "2018-08-05T13:43:11.82Z"
},{
Name: "Item3",
Date: "2018-08-04T13:43:11.82Z"
},{
Name: "Item4",
Date: "2018-08-03T13:43:11.82Z"
}
];
$scope.search = {};
$scope.$watch('search', function (newVal, oldVal) {
$scope.filtered = filterFilter($scope.list, newVal);
}, true);
});
working example:
http://plnkr.co/edit/O7j1DAzoxArHK4mnjyeP?p=info
How can I alter this, so I can type the date-value as formatted?
At this case you should create custom filter:
angular.module('plunker', []).controller('MainCtrl', function($scope) {
$scope.list = [{
Name: "Item1",
Quantity: 21,
Date: "2018-08-06T13:43:11.82Z"
}, {
Name: "Item2",
Quantity: 20,
Date: "2018-08-05T13:43:11.82Z"
}, {
Name: "Item3",
Quantity: 31,
Date: "2018-08-04T13:43:11.82Z"
}, {
Name: "Item4",
Quantity: 25,
Date: "2018-08-03T13:43:11.82Z"
}];
$scope.search = {};
}).filter('custom', function() {
return function(array, search) {
function Norm(x) {
return (x + '').toLocaleLowerCase();
}
return array.filter(function(x) {
for (var prop in search) {
if (prop != 'Date' && search[prop] &&
Norm(x[prop]).indexOf(Norm(search[prop])) == -1)
return false;
}
if (x.Date) {
var formatted = x.Date.substring(0, 10).split('-').reverse().join('-');
if (search.Date && !formatted.startsWith(search.Date))
return false;
return true;
}
});
}
});
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<body ng-app='plunker' ng-controller="MainCtrl">
Name: <input type="text" ng-model="search.Name">
<br> Quantity: <input type="text" ng-model="search.Quantity">
<br> Date: <input type="text" ng-model="search.Date">
<br>
<table>
<tr ng-repeat="item in list | custom : search | orderBy : 'Quantity'">
<td>{{item.Name}}</td>
<td>{{item.Quantity}}</td>
<td>{{item.Date | date:'dd-MM-yyyy'}}</td>
</tr>
</table>
</body>
Html:
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS</title>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
Name:
<input type="text" ng-model="search.Name">
<br>
Date:
<input type="text" ng-model="search.Date">
<table>
<tr ng-repeat="item in list2 | filter : search.Date">
<td>{{item.Name}}</td>
<td>{{item.Date}}</td>
</tr>
</table>
</body>
</html>
Js:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $filter) {
const list = [{
Name: "Item1",
Date: "2018-08-06T13:43:11.82Z"
},{
Name: "Item2",
Date: "2018-08-05T13:43:11.82Z"
},{
Name: "Item3",
Date: "2018-08-04T13:43:11.82Z"
},{
Name: "Item4",
Date: "2018-08-03T13:43:11.82Z"
}
];
$scope.list2 = list.map(x => (
{
Name: x.Name,
Date: $filter('date')(x.Date, 'dd-MM-yyyy')
})
);
});

I was doing a functionality in Angular JS, When I search and click on button, related search data has to display using ng-click and ng-repeat

<script>
var app = angular.module("myApp", ['ngRoute']);
app.controller("myCtrl", function($scope) {
$scope.srch = [{
name: "Rani",
phno:"145365463"
},
{
name: "Raj",
phno:"989365463"
},
{
name: "Sai",
phno:"782144635"
},
{
name: "roja",
phno:"5365463889"
},
{
name: "Priya",
phno:"321565463"
}
]
</script>
<html>
<head>
<title>Sample</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<div>
<input type="text" ng-model="search" placeholder="Search for name or email" style="width:200px;"></input>
<table class="table table-striped" ng-show="search">
<tr ng-repeat="y in srch | filter: search">
<td>{{y.name}}</td>
<td>{{y.phno}}</td>
</tr>
</table>
</div>
</body>
</html>
First point, input tag has no end tag.
Then, your AngularJS script is false. Controller code is never closed.
var app = angular.module("myApp", ['ngRoute']);
app.controller("myCtrl", function($scope) {
$scope.srch = [{
name: "Rani",
phno:"145365463"
},
{
name: "Raj",
phno:"989365463"
},
{
name: "Sai",
phno:"782144635"
},
{
name: "roja",
phno:"5365463889"
},
{
name: "Priya",
phno:"321565463"
}
];
}); // Don't forget to close
Avoid declaring ngApp and ngController on same element.
See this Plunkr working: https://plnkr.co/edit/n1lJ4uSdM5Nc7xZxM7XB?p=preview
You have to type some chars to make your list appear. What I can recommend to you is to filter your ngRepeat with a function instead of variable.

md-data-table is giving errors "Cannot read property 'length' of undefined"

This is my first project with angularjs. I'm using md-data-table for angular material web app. I installed md-data-table and it started asking for lodash. So I installed lodash. That's when I got this [error][1]. So I thought maybe angular-lodash might help, and I got another error that says _.methods is not a function. I found some posts about lodash does not support certain functions anymore. But I can't seem to find anything useful to my case. What am i missing here?
Code:
var app = angular.module('app', [
'ngMaterial',
'ngMaterialSidemenu',
'mdPickers',
'ui.grid',
'mdDataTable']);
app.controller('appCtrl', function ($scope, $mdDialog, $mdpTimePicker) {
$scope.items = [1, 2, 3, 4, 5];
$scope.selectedItem = $scope.items[0];
$scope.getSelectedText = function () {
if ($scope.selectedItem != undefined) {
return 'You chose ' + $scope.selectedItem + '.';
} else {
return 'Choose an item.';
}
};
$scope.selectedTime = $scope.selectedDate = new Date();
$scope.message = 'Hello';
// directive
$scope.point = {
pointId: '1001'
};
$scope.browser = function (ev) {
var searchByColumns = [
'Point ID',
'Description'
];
var pointList = [{
pointId: '1001',
description: 'point 1'
}, {
pointId: '1002',
description: 'point 2'
}, {
pointId: '1003',
description: 'point 3'
}];
$mdDialog.show({
templateUrl: '/dialogs/browser/grid-browser.html',
parent: angular.element(document.body),
targetEvent: ev,
locals: {
items: pointList,
searchByColumns: searchByColumns
},
openFrom: '#searchBtn',
clickOutsideToClose: true,
controller: function ($scope, items, searchByColumns) {
$scope.items = items;
$scope.searchByColumns = searchByColumns;
$scope.selectedColumn = $scope.searchByColumns[0];
$scope.getSelectedText = function () {
return $scope.selectedColumn;
};
}
})
// .then(function (answer) {
// $scope.status = 'You said the information was "' + answer + '".';
// }, function () {
// $scope.status = 'You cancelled the dialog.';
// })
;
};
$scope.nutritionList = [{
id: 601,
name: 'Frozen joghurt',
calories: 159,
fat: 6.0,
carbs: 24,
protein: 4.0,
sodium: 87,
calcium: '14%',
iron: '1%'
}, {
id: 602,
name: 'Ice cream sandwitch',
calories: 237,
fat: 9.0,
carbs: 37,
protein: 4.3,
sodium: 129,
calcium: '84%',
iron: '1%'
}, {
id: 603,
name: 'Eclair',
calories: 262,
fat: 16.0,
carbs: 24,
protein: 6.0,
sodium: 337,
calcium: '6%',
iron: '7%'
}];
});
<html lang="en">
<head>
<link rel="stylesheet" href="/node_modules/angular-material/angular-material.css"></link>
<link rel="stylesheet" href="/node_modules/angular-material-sidemenu/dist/angular-material-sidemenu.css"></link>
<link rel="stylesheet" href="/node_modules/mdPickers/dist/mdPickers.css"></link>
<link rel="stylesheet" href="/node_modules/angular-material-time-picker/dist/md-time-picker.css"></link>
<link rel="stylesheet" href="/assets/md-data-table/md-data-table.min.css"></script>
<link rel="stylesheet" href="/assets/css.css"></link>
<link rel="stylesheet" href="/assets/icons.css"></link>
<link rel="stylesheet" href="/assets/ui-grid/ui-grid.min.css"></link>
<link rel="stylesheet" href="/main.css"></link>
</head>
<body ng-app="app" ng-controller="appCtrl" ng-cloak>
<md-toolbar class="md-primary">
<div class="md-toolbar-tools">
<h2 class="md-flex">HTML 5</h2>
</div>
</md-toolbar>
<md-content layout-padding layout="row">
<md-sidemenu locked="false">
<md-sidemenu-group>
<md-sidemenu-content md-icon="home" md-heading="Master" md-arrow="true">
<md-sidemenu-button ng-href="#pointMaster">Point</md-sidemenu-button>
<md-sidemenu-button href="#">Submenu 2</md-sidemenu-button>
<md-sidemenu-button href="#">Submenu 3</md-sidemenu-button>
</md-sidemenu-content>
<md-sidemenu-content md-heading="Menu 2" md-arrow="true">
<md-sidemenu-button href="#">Submenu 1</md-sidemenu-button>
<md-sidemenu-button href="#">Submenu 2</md-sidemenu-button>
<md-sidemenu-button href="#">Submenu 3</md-sidemenu-button>
</md-sidemenu-content>
</md-sidemenu-group>
<md-sidemenu-group>
<md-divider></md-divider>
<md-subheader class="md-no-sticky">Caption</md-subheader>
<md-sidemenu-button href="#">Menu 4</md-sidemenu-button>
</md-sidemenu-group>
</md-sidemenu>
<md-tabs md-dynamic-height md-border-bottom flex="75">
<md-tab label="Tax">
<form flex>
<div layout="row" layout-align="start center">
<input-button flex="50" md-margin required="false" label="Point ID" tableId="point.pointId" browse="browser()"></input-button>
<span style="width: 20px"></span>
<md-checkbox aria-label="Default" class="md-primary" layout-align="center center" flex>
Default
</md-checkbox>
</div>
<div layout="row">
<md-input-container>
<label>Items</label>
<md-select ng-model="selectedItem" md-selected-text="getSelectedText()">
<md-optgroup label="items">
<md-option ng-value="item" ng-repeat="item in items">Item {{item}}</md-option>
</md-optgroup>
</md-select>
</md-input-container>
<mdp-time-picker mdp-auto-switch="true" ng-model="selectedTime" message="message">
</mdp-time-picker>
</div>
<div layout="row" flex>
<md-button class="md-raised md-primary">Save</md-button>
<md-button class="md-raised md-warn">Delete</md-button>
<md-button class="md-raised md-primary" ng-disabled="true">Reset</md-button>
</div>
<div layout="row" flex>
<md-datepicker ng-model="selectedDate" md-placeholder="Enter date" layout-align="start center" md-open-on-focus>
</md-datepicker>
</div>
</form>
</md-tab>
<md-tab label="Family" layout="column" flex>
<mdt-table mdt-row="{'data': nutritionList, 'table-row-id-key': 'id',
'column-keys': ['name', 'calories', 'fat', 'carbs', 'protein', 'sodium', 'calcium', 'iron']}">
<mdt-header-row>
<mdt-column align-rule="left">Dessert (100g serving)</mdt-column>
<mdt-column align-rule="right">Calories</mdt-column>
<mdt-column align-rule="right">Fat (g)</mdt-column>
<mdt-column align-rule="right">Carbs (g)</mdt-column>
<mdt-column align-rule="right">Protein (g)</mdt-column>
<mdt-column align-rule="right">Sodium (mg)</mdt-column>
<mdt-column align-rule="right">Calcium (%)</mdt-column>
<mdt-column align-rule="right">Iron (%)</mdt-column>
</mdt-header-row>
<mdt-custom-cell column-key="Dessert" ng-click="viewFats(value)">
<span ng-repeat="name in names">{{value}}</span>
</mdt-custom-cell>
</mdt-table>
</md-tab>
</md-tabs>
</md-content>
</body>
<script src="/node_modules/angular/angular.js"></script>
<script src="/node_modules/angular-animate/angular-animate.js"></script>
<script src="/node_modules/angular-aria/angular-aria.js"></script>
<script src="/node_modules/angular-messages/angular-messages.js"></script>
<script src="/node_modules/moment/moment.js"></script>
<script src="/node_modules/angular-moment/angular-moment.js"></script>
<script src="/node_modules/angular-material/angular-material.js"></script>
<script src="/node_modules/angular-sanitize/angular-sanitize.min.js"></script>
<script src="/node_modules/angular-material-sidemenu/dist/angular-material-sidemenu.js"></script>
<script src="/node_modules/mdPickers/dist/mdPickers.js"></script>
<script src="/node_modules/angular-material-time-picker/dist/md-time-picker.js"></script>
<script src="/assets/lodash/lodash.min.js"></script>
<script src="/assets/md-data-table/md-data-table.min.js"></script>
<script src="/assets/md-data-table/md-data-table-templates.min.js"></script>
<script src="/assets/ui-grid/ui-grid.min.js"></script>
<script src="/assets/angular-material-icons.min.js"></script>
<script src="/app.js"></script>
<script src="/directives/input-button/input-button.js"></script>
<script src="/dialogs/browser/grid-browser.js"></script>
</html>
ps://i.stack.imgur.com/WmdiC.png
#Htet Aung,
The code snippet provided by you does not have valid md-data-table tags in html and also errors while injecting md-data-table. For your information you are using "mdDataTable" which was designed for ANGULAR (angular2) version. But looking at your code suggests you need md-data-table for Angularjs(version 1.x).
No Need for loadash libraries. just normal md-data-table.js from cdnjs will do and inject the dependency 'md.data.table' in your module.
Please find the below :
[MD Data Table for AngularJs Material and Angularjs 1.x version]
[1]: https://codepen.io/anon/pen/BjvLVJ?editors=1010

Angularjs Ng-repeat with search filter only works on 2nd character keyup

I have implemented basic Angularjs search filter but it only work when I enter 2nd character in input box.
<input type="text" ng-model="search" class="search-input" id="search-input"><div ng-repeat="x in publishList | filter:search"></div>
I have implemented the same and is working, not sure why it is not working for you.
How ever can you try this?
<input type="text" ng-model="search.scheduleName" class="search-input" id="search-input">
I have tried with the code and the array you've given and it works for me.
Could you create a jsfiddle or plnkr example illustrating the problem ?
angular
.module('demo', [])
.controller('DefaultController', DefaultController);
function DefaultController() {
var vm = this;
vm.items = [
{ scheduleName : 'Forrest' },
{ scheduleName : 'Gump' },
{ scheduleName : 'saw' },
{ scheduleName : 'xmen' },
{ scheduleName : 'troy' }
];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<input type="text" ng-model="ctrl.search"/>
<div ng-repeat="item in ctrl.items | filter : ctrl.search">
{{item.scheduleName}}
</div>
</div>
</div>
You can also filter by an object's property in the array by using any one of the two approaches given below.
Specifying the property to filter in the AngularJS built-in filter called filter.
angular
.module('demo', [])
.controller('DefaultController', DefaultController);
function DefaultController() {
var vm = this;
vm.items = [
{ id: 1, scheduleName : 'Forrest' },
{ id: 2, scheduleName : 'Gump' },
{ id: 3, scheduleName : 'saw' },
{ id: 4, scheduleName : 'xmen' },
{ id: 5, scheduleName : 'troy' }
];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<input type="text" ng-model="ctrl.search"/>
<div ng-repeat="item in ctrl.items | filter : { scheduleName: ctrl.search }">
{{item.id}}. {{item.scheduleName}}
</div>
</div>
</div>
Specifying an object to be used to filter - this is more dynamic.
angular
.module('demo', [])
.controller('DefaultController', DefaultController);
function DefaultController() {
var vm = this;
vm.items = [
{ id: 1, scheduleName : 'Forrest' },
{ id: 2, scheduleName : 'Gump' },
{ id: 3, scheduleName : 'saw' },
{ id: 4, scheduleName : 'xmen' },
{ id: 5, scheduleName : 'troy' }
];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<input type="text" ng-model="ctrl.search.scheduleName"/>
<div ng-repeat="item in ctrl.items | filter : ctrl.search">
{{item.id}}. {{item.scheduleName}}
</div>
</div>
</div>

Angular: Uncaught ReferenceError: myFunction is not defined

I'm creating a contacts list and i'm using Angular for the first time.
I created an attribute directive for the table rows (that i use inside the table tag), in which i add a controller to handle click on a button, that deletes the row removing it from the table.
All works well, but i get an error in the browser console.
Here you can see the output of my source code:
When i try to delete a contact (i press on the button with the trash as icon) it works, but in the Chrome console i get this error:
Uncaught ReferenceError: delUser is not defined
You can see it here:
Here is my code:
index.html
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>Rubrica</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body ng-controller="myCtrl">
<section id="panel">
<button class="panel_btn" ng-click="showHideAdd()"><i class="fa fa-plus"></i> Aggiungi</button>
<button class="panel_btn" ng-click="showHideSearch()"><i class="fa fa-search"></i> Cerca</button>
</section>
<section id="list">
<table width="50%">
<thead>
<tr>
<th>Nome<span ng-show="sortType == 'name' && !sortReverse" class="fa fa-caret-down"></span><span ng-show="sortType == 'name' && sortReverse" class="fa fa-caret-up"></span></th>
<th>Cognome<span ng-show="sortType == 'surname' && !sortReverse" class="fa fa-caret-down"></span><span ng-show="sortType == 'surname' && sortReverse" class="fa fa-caret-up"></span></th>
<th>Telefono<span ng-show="sortType == 'phone' && !sortReverse" class="fa fa-caret-down"></span><span ng-show="sortType == 'phone' && sortReverse" class="fa fa-caret-up"></span></th>
<th>Operazioni</th>
</tr>
</thead>
<tbody>
<tr ng-hide="isSearchVisible">
<td><input name="nameSearch" placeholder="Cerca nome" ng-model="search.name"></input></td>
<td><input name="surnameSearch" placeholder="Cerca cognome" ng-model="search.surname"></input></td>
<td><input name="phoneSearch" placeholder="Cerca telefono" ng-model="search.phone"></input></td>
</tr>
<tr userdir item="user" onclick="delUser" ng-repeat="user in users | orderBy:sortType:sortReverse | filter:search">
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">Totale utenti: {{getTotal()}}</td>
</tr>
</tfoot>
</table>
</section>
<section id="tools">
<form name="addForm" ng-show="isAddVisible" novalidate>
<p>Compila tutti i campi</p>
<input type="text" name="nameToAdd" placeholder="Nome" ng-model="formName" required ng-minlength="3"><br /><small ng-show="isInvalid && (addForm.nameToAdd.$error.required || addForm.nameToAdd.$error.minlength)">Il nome deve avere almeno 3 lettere</small><br />
<input type="text" name="surnameToAdd" placeholder="Cognome" ng-model="formSurname" required ng-minlength="3"><br /><small ng-show="isInvalid && (addForm.surnameToAdd.$error.required || addForm.surnameToAdd.$error.minlength)">Il cognome deve avere almeno 3 lettere</small><br />
<input type="tel" name="phoneToAdd" placeholder="Telefono" ng-model="formPhone" required ng-pattern="/^\d{2,4}/\d{5,8}/"><br /><small ng-show="isInvalid && (addForm.phoneToAdd.$error.required || addForm.phoneToAdd.$error.pattern)">Inserisci un numero di telefono valido</small><br />
<button ng-click="add()"><i class="fa fa-save fa-lg"></i> Salva</button>
</form>
<form name="searchForm" ng-submit="search()" ng-show="isSearchVisible" novalidate>
<p>Cerca utenti</p>
<input type="text" name="stringToFind" placeholder="Cerca..." ng-model="search.$" required><br />
</form>
</section>
</body>
</html>
app.js
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', ['$scope', '$timeout', function($scope, $timeout) {
$scope.sortType = 'name';
$scope.sortReverse = false;
$scope.isInvalid = false;
$scope.users = [{
name: 'Mario',
surname: 'Rossi',
phone: '084/8465645'
}, {
name: 'Giuseppe',
surname: 'Bianchi',
phone: '06/548484'
}, {
name: 'Luca',
surname: 'Verde',
phone: '0984/3214867'
}, {
name: 'Luigi',
surname: 'Roma',
phone: '0775/3214867'
}];
$scope.getTotal = function() {
return $scope.users.length;
};
$scope.add = function() {
if ($scope.addForm.$valid) {
$scope.users.push({
name: $scope.formName,
surname: $scope.formSurname,
phone: $scope.formPhone
});
$scope.formName = '';
$scope.formSurname = '';
$scope.formPhone = '';
} else {
$scope.isInvalid = true;
}
};
$scope.isAddVisible = false;
$scope.showHideAdd = function() {
$scope.isAddVisible = $scope.isAddVisible ? false : true;
$scope.isSearchVisible = false;
};
$scope.isSearchVisible = false;
$scope.showHideSearch = function() {
$scope.isSearchVisible = $scope.isSearchVisible ? false : true;
$scope.isAddVisible = false;
};
$scope.delUser = function(user) {
var index = $scope.users.indexOf(user);
$scope.users.splice(index, 1);
};
}]);
myApp.directive('userdir', function() {
return {
restrict: 'A',
templateUrl: 'views/userRow.html',
controller: function($scope) {
$scope.delete = function() {
$scope.onclick($scope.item);
};
},
controllerAs: 'ctrl',
scope: {
item: '=',
onclick: '='
}
};
});
userRow.html
<tr>
<td>{{item.name}}</td>
<td>{{item.surname}}</td>
<td>{{item.phone}}</td>
<td><button ng-click="delete()"><i class="fa fa-trash"></i></button>
</tr>
Renaming onclick to any other word inside my directive's scope makes it working.
The glitch may happen because onclick is a reserved word for HTML.
It looks like your "ng-click=delete()" already calls the delUser function.
Why do you need the onclick="delUser" in index.html?
Also if this a function should it be onclick="delUser()"?

Resources