im making a simple app, that can add a name and a description in a table.
But im getting the error of - Cannot read property 'push' of undefined.
Could some one help me ?
this is my code.
HTML
<div id="main">
<!-- angular templating -->
<!-- this is where content will be injected -->
<div ng-view>
</div>
</div>
JS
var scotchApp = angular.module('scotchApp', ['ngRoute','dx']);
scotchApp.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode({ enabled: true, requireBase: false });
$routeProvider
// route for the home page
.when('/', {
templateUrl: '/pages/home.html',
controller: 'mainController'
})
.when('/new', {
templateUrl: '/pages/edit.html',
controller: 'newController'
});
})
scotchApp.controller('newController', function ($scope, $location) {
$scope.person = { name: "", description: "" };
$scope.save = function () {
$scope.crew.push($scope.person);
$location.path("/")
}
});
scotchApp.controller('mainController', function ($scope) {
$scope.crew = [
{ name: "Hugo", description: "Programador" },
{ name: "Vitor Lopes", description: "Técnico de Informática" },
{ name: "Pedro Sousa", description: "Webdesigner" },
]
});
HTML - new.html ( page where i have my table)
<table class="table table-striped" style="width: 350px;">
<thead>
<tr>
<td><strong>Nome</strong></td>
<td><strong>Descrição</strong></td>
<td><i class="glyphicon glyphicon-plus"></i></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in crew">
<td>{{person.name}}</td>
<td>{{person.description}}</td>
<td><i class="glyphicon glyphicon-edit"></i></td>
</tr>
</tbody>
</table>
HTML - new.html ( page where i will add my new contact)
<form>
<input ng-model="person.name" placeholder="Enter Name"/><br />
<input ng-model="person.description" placeholder="Enter Description" /><br />
<button ng-click="save()" class="btn-primary">Save</button>
Thank You !!
define your array before push something like so :
$scope.crew = []
Related
I am making my first AngularJS App followed by this tutorial:
https://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app
The problem is in my App when I direct to view 1, it works fine. It can load the HTML file with the information of all the drivers. However, when I click one specific driver, it can't load the HTML page for the particular driver. How can I redirect to the HTML page of the particular driver?
The App structure is
view 1:
view1.html
js
driver
---------driver.html
view 2
view2.html
<p>This is the partial for view 1.</p>
<input type="text" ng-model="filterTxn.Driver.givenName" placeholder="Search..."/>
<table>
<thead>
<tr><th colspan="4">Drivers Championship Standings</th></tr>
</thead>
<tbody>
<tr ng-repeat="driver in driversList | filter: filterTxn ">
<td>{{$index + 1}}</td>
<td>
<a href="#/view1/driver/{{driver.Driver.driverId}}">
{{driver.Driver.givenName}} {{driver.Driver.familyName}}
</a>
</td>
<td>{{driver.Constructors[0].name}}</td>
<td>{{driver.points}}</td>
</tr>
</tbody>
</table>
<p>detail page for a specific driver</p>
<section id="main">
<- Back to drivers list
<nav id="secondary" class="main-nav">
<div class="driver-picture">
<div class="avatar">
<img ng-show="driver" src="img/drivers/{{driver.Driver.driverId}}.png" />
<img ng-show="driver" src="img/flags/{{driver.Driver.nationality}}.png" /><br/>
{{driver.Driver.givenName}} {{driver.Driver.familyName}}
</div>
</div>
<div class="driver-status">
Country: {{driver.Driver.nationality}} <br/>
Team: {{driver.Constructors[0].name}}<br/>
Birth: {{driver.Driver.dateOfBirth}}<br/>
Biography
</div>
</nav>
<div class="main-content">
<table class="result-table">
<thead>
<tr><th colspan="5">Formula 1 2013 Results</th></tr>
</thead>
<tbody>
<tr>
<td>Round</td> <td>Grand Prix</td> <td>Team</td> <td>Grid</td> <td>Race</td>
</tr>
<tr ng-repeat="race in races">
<td>{{race.round}}</td>
<td><img src="img/flags/{{race.Circuit.Location.country}}.png" />{{race.raceName}}</td>
<td>{{race.Results[0].Constructor.name}}</td>
<td>{{race.Results[0].grid}}</td>
<td>{{race.Results[0].position}}</td>
</tr>
</tbody>
</table>
</div>
</section>
view1.js:
'use strict';
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', [function() {
}]);
angular.module('F1FeederApp', [
'F1FeederApp.services',
'F1FeederApp.controllers',
'ngRoute'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when("/drivers/:id", {templateUrl: "view1/driver/driver.html", controller: "driverController"}).
otherwise({redirectTo: '/view1'});
}]);
services.js:
angular.module('F1FeederApp.services', [])
.factory('ergastAPIservice', function($http) {
var ergastAPI = {};
ergastAPI.getDrivers = function() {
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/2013/driverStandings.json?callback=JSON_CALLBACK'
});
}
ergastAPI.getDriverDetails = function(id) {
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/2013/drivers/'+ id +'/driverStandings.json?callback=JSON_CALLBACK'
});
}
ergastAPI.getDriverRaces = function(id) {
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/2013/drivers/'+ id +'/results.json?callback=JSON_CALLBACK'
});
}
return ergastAPI;
});
angular.module('F1FeederApp.controllers', []).
/* Drivers controller */
controller('driversController', function($scope, ergastAPIservice) {
$scope.nameFilter = null;
$scope.driversList = [];
$scope.searchFilter = function (driver) {
var re = new RegExp($scope.nameFilter, 'i');
return !$scope.nameFilter || re.test(driver.Driver.givenName) || re.test(driver.Driver.familyName);
};
ergastAPIservice.getDrivers().success(function (response) {
//Digging into the response to get the relevant data
$scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings;
});
}).
/* Driver controller */
controller('driverController', function($scope, $routeParams, ergastAPIservice) {
$scope.id = $routeParams.id;
$scope.races = [];
$scope.driver = null;
ergastAPIservice.getDriverDetails($scope.id).success(function (response) {
$scope.driver = response.MRData.StandingsTable.StandingsLists[0].DriverStandings[0];
});
ergastAPIservice.getDriverRaces($scope.id).success(function (response) {
$scope.races = response.MRData.RaceTable.Races;
});
});
Use ui-sref instead of href to trigger the state change.
<p>This is the partial for view 1.</p>
<input type="text" ng-model="filterTxn.Driver.givenName" placeholder="Search..."/>
<table>
<thead>
<tr><th colspan="4">Drivers Championship Standings</th></tr>
</thead>
<tbody>
<tr ng-repeat="driver in driversList | filter: filterTxn ">
<td>{{$index + 1}}</td>
<td>
<a ui-sref="/driver/{{driver.Driver.driverId}}">
{{driver.Driver.givenName}} {{driver.Driver.familyName}}
</a>
</td>
<td>{{driver.Constructors[0].name}}</td>
<td>{{driver.points}}</td>
</tr>
</tbody>
</table>
I am trying to search using angularjs filter method but its not working. I am not getting any errors in the console but still the search result is not showing up. Can someone help me on this.
This is my controller.js code:
.controller('SearchController',
[
'$scope',
'dataService',
'$location',
'$routeParams',
function ($scope, dataService, $location, $routeParams){
$scope.searchMovies = [ ];
$scope.searchCount = 0;
var getSearchResult = function (terms) {
dataService.getSearchResult(terms).then(
function (response) {
$scope.searchCount = response.rowCount + ' movies';
$scope.searchMovies = response.data;
$scope.showSuccessMessage = true;
$scope.successMessage = "All movie Success";
},
function (err){
$scope.status = 'Unable to load data ' + err;
}
); // end of getStudents().then
};
if ($routeParams && $routeParams.term) {
console.log($routeParams.term);
getSearchResult($routeParams.term);
}
}
]
);
This is the services.js code:
this.getSearchResult = function (terms) {
var defer = $q.defer(),
data = {
action: 'search',
term: terms
}
$http.get(urlBase, {params: data, cache: true}).
success(function(response){
defer.resolve({
data: response.ResultSet.Result,
rowCount: response.RowCount
});
}).
error(function(err){
defer.reject(err);
});
return defer.promise;
};
This is my app.js code:
. when('/search', {
templateUrl : 'js/partials/search.html',
controller : 'SearchController'
}).
This is the search.html code:
<div>
<label>Search: <input ng-model="searchMovie"></label><br><br><br><br>
</div>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="search in searchMovies | filter:searchMovie">
<td>
{{search.title}}
</td>
<td>
{{search.description}}
</td>
<td>
{{search.name}}
</td>
</tr>
</tbody>
</table>
The search data is being retrieved from the database. I have tested the SQL and it works fine. Just thee problem is in the angularjs server side. Thank you.
You need to give Alias for controller in your app.js file
.when('/search', {
templateUrl : 'js/partials/search.html',
controller : 'SearchController'
controllerAs: 'movies',
});
Now After This in your search.html file pass controllerAs
<div>
<label>Search: <input ng-model="searchMovie"></label><br><br><br><br>
</div>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="search in searchMovies | filter:searchMovie">
<td>
{{movies.search.title}}
</td>
<td>
{{movies.search.description}}
</td>
<td>
{{movies.search.name}}
</td>
</tr>
</tbody>
I have a view which displays List of my database and it works!
All I want to do is to pass a variable named "search1" from view to server side Controller Thats ALL!
View
<section data-ng-controller="AllsController" data-ng-init="find()">
<div class="page-header">
<h1>Alls</h1>
</div>
<div class="Search">
<select data-ng-model="search1" id="search">
<option value="Model1">Jeans</option>
<option value="Model2">Shirts</option>
</select>
</div>
<br></br><br></br>
<h2>Result Section</h2>
<div class="list-group">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Created</th>
<th>User</th>
<th>Brand</th>
<th>Color</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="all in alls">
<td data-ng-bind="all.created | date:'medium'"></td>
<td data-ng-bind="all.user.displayName"></td>
<td data-ng-bind="all.name"></td>
<td data-ng-bind="all.color"></td>
</tr>
</tbody>
</table>
</div>
Client Controller
angular.module('alls').controller('AllsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Alls', 'Jeans', function($scope, $stateParams, $location, Authentication, Alls, Jeans) {
$scope.find = function() {
$scope.alls = Alls.query();
}; }]);
Service
angular.module('alls').factory('Alls', ['$resource',
function($resource) {
return $resource('alls/:allId', { allId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}]);
Server Controller
exports.list = function(req, res) {
var search1 = req.search1 ;
if (search1 === 'Jeans' )
{
Jeans.find().sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
res.jsonp(jeans);
});
} }
Server Route
module.exports = function(app) {
var alls = require('../../app/controllers/alls.server.controller');
app.route('/alls')
.get(alls.list);}
I should be able to see Jeans Model when it is chosen but it does not show me Jeans Model
I think I have not passed "search1" to the server Controller properly and I need to change my client Controller or Server Route;
But I do not know how!
Any idea or example would be helpful,
Thanks!
I think you need to change
var search1 = req.search1;
to
var search1 = req.params.search1;
I'm using angularjs. What i want to do is when user click button , angularjs will checking item id in database. If item id exist in database, #modal will be showed instead of alert like this question. Is it possible to do this with angularjs? If possible how..
HTML
<div id="container" ng-app='two_way' ng-controller="aa" >
<div align="center">
<h1 align="center"> Nutrition Scheduling List </h1>
<button ng-click="loadsched()" >LOAD SCHEDULE</button>
</div>
<span ng-hide="load==null">
<table border='1' bgcolor="CCFFFF" align="center">
<tr ><td><b>Item Name</b></td><td><b>Scheduled Time</b></td><td><b>Run Time</b></td><td><b>Create Time</b></td><td><b>Status</b></td><td><b>Response</b></td></tr>
<tr ng-repeat="data in load | orderBy: 'searchitem'">
<td>
{{data.searchitem}}
</td>
<td>
{{data.Scheduledtime}}
</td>
<td>
{{data.runt}}
</td>
<td>
{{data.CurrentTime}}
</td>
<td>
{{data.STATUS}}
</td>
<td>
<input type="button" class="btn btn-lg btn-primary" value="RESPONSE" onclick="window.open('http://localhost:3000/search/{{data._id}}','popUpWindow','height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');">
</td>
</tr>
</table>
</span>
<script src="more.js"></script>
</div>
Controller more.js
var app=angular.module('two_way', ['ui.bootstrap']);
app.controller('aa',function($scope,$http){
$scope.loadsched=function(){
$http.post("http://localhost:3000/a").success(function(data){
//console.log(data);
$scope.load=angular.fromJson(data);
}).error(function(){alert("Error");});
}
});
Very simple :-
1) Apply $modal to your main controller.
2) Use $modal.open() to open modal anywhere and it will return a promise.
$modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size
);
Here template is file or Id of your modal template.
size:sm,lg
Controller it is the controller of your modal.
For example:-
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
$modalInstance service is used to close and return the promise from modal.
$modalInstance.close($scope.selected.item); close the modal and return data to controller.
$modalInstance.dismiss('cancel'); it is simply dismiss the controller.
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
Here modalInstance.result is used to get data from modal controller to your main controller.
Official Plunker
The following bit of code has a shell page index.html and a partial view (which is currently being used by two different controllers). The hard-coded data in AppController is wired into the list.html partial view and rendered as a table. In the JS I added a console.log to see when the controllers were being invoked. When the app loads up
AppController fires, when I invoke #/new, NewController fires. However, when I click on the edit button which is next to each row, the EditController isn't being called. EditController should use the /partials/edit.html view but populate the fields with the information of the row that was clicked on. So crew[0] in this example is Picard and his data should be pre-populated when you click on that icon. I'm not getting any errors, but the EditController's view isn't being injected when it should be.
JS
angular.module('enterprise', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when("/", { templateUrl: "/partials/list.html" })
.when("/new", { templateUrl: "/partials/edit.html", controller: "NewController" })
.when("/edit:id", { templateUrl: "/partials/edit.html", controller: "EditController" });
})
//this is the that iterated over in the partial views ng-repeat
function AppController($scope){
$scope.crew = [
{ name: 'Picard', description: 'captain' },
{ name: 'Riker', description: 'number 1' },
{ name: 'Word', description: 'Security' }
];
console.log('app controller hit');
}
function NewController($scope, $location) {
$scope.person = { name: "", description: "" };
$scope.save = function () {
$scope.crew.push($scope.person);
$location.path("/");
}
console.log('new controller hit');
}
function EditController($scope, $location,$routeParams) {
$scope.person = $scope.crew[$routeParams.id];
console.log('edit controller hit');
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>Angular JS Routing</title>
<link rel="stylesheet"
href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"/>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css"
rel="stylesheet">
</head>
<body>
<div ng-app="enterprise" ng-controller="AppController">
<h2>Enterprise Crew</h2>
<ng-view></ng-view>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
list.html
<table class="table table-striped" style="width: 250px">
<thead>
<tr>
<td>Name</td>
<td>Description</td>
<td> <i class="glyphicon glyphicon-plus-sign"></i>
</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in crew">
<td>{{person.name}}</td>
<td>{{person.description}}</td>
<td><i class="glyphicon glyphicon-edit"></i></td>
as ng-repeat loops through I'm trying to go to the edit.hml partial view and populate the text boxes in `edit.html` with the data from the row that was clicked on
</tr>
</tbody>
</table>
edit.html
<form action="">
<input ng-model="person.name"/ placeholder="Enter the person name">
<input ng-model="person.description"/ placeholder="Enter the description">
<button ng-click="save()" class="btn-primary">Save</button>
</form>
I'm not getting any errors, but my EditController is never being fired. Can someone let me know why? Thanks.
"/edit:id" should instead be "/edit/:id" in
.when("/edit:id", { templateUrl: "/partials/edit.html", controller: "EditController" });