Angular JS passing ng-repeat $index as parameter - javascript

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" });

Related

angularjs without controller ng-click not firing

I am practising angularjs. In below example, ng-click is not firing at all, not sure why. I actually not using any controller in my code, may be because of that, ng-click not firing?
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="myApp1">
<div ng-init="users=[{name: 'john', city: 'NY', order: 10},{name: 'james', city: 'washington', order: 20},{name: 'william', city: 'seattle', order: 30}]">
<h2>Customers</h2>
Search Customer: <input type="text" ng-model="searchText" placeholder="search customer here">
<br><br>
<table border="2">
<thead>
<tr>
<th ng-click="orderByProperty('name')">Name</th>
<th ng-click="orderByProperty('city')">City</th>
<th ng-click="orderByProperty('order')">Order</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users | filter : searchText | orderBy : orderByProperty : true">
<td>{{user.name | uppercase}}</td>
<td>{{user.city}}</td>
<td>{{user.order | currency}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
app.js
var myApp1 = angular.module('myApp1',[])
function orderByProperty(propertyName){
// alert('dsfdf')
return propertyName;
}
Please tell me what went wrong in above code? Is that mandatory to use controller in a code? If not used, ng-click do not work at all?
UPDATE
When I replaced ng-click with 'onclick', even is getting fired, but sorting functionality is not working.
UPDATE2: BELOW IS THE UPDATED CODE
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="myApp1">
<div ng-controller="MyController">
<div ng-init="users=[{name: 'john', city: 'NY', order: 10},{name: 'james', city: 'washington', order: 20},{name: 'william', city: 'seattle', order: 30}]">
<h2>Customers</h2>
Search Customer: <input type="text" ng-model="searchText" placeholder="search customer here">
<br><br>
<table border="2">
<thead>
<tr>
<th ng-click="orderByProperty('name')">Name</th>
<th ng-click="orderByProperty('city')">City</th>
<th ng-click="orderByProperty('order')">Order</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users | filter : searchText | orderBy : orderByProperty : true">
<td>{{user.name | uppercase}}</td>
<td>{{user.city}}</td>
<td>{{user.order | currency}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
app.js
var myApp1 = angular.module('myApp1',[])
myApp1.controller('MyController', ['$scope', function($scope){
$scope. orderByProperty = function(propertyName){
// alert('dsfdf')
return propertyName;
}
}])
Above I used controller, now evenT gets firing but sorting not working as expected..
Yes you need to have the ng-controller placed in order to get ng-click work.
When a controller is attached to the DOM via the ng-controller
directive, Angular will instantiate a new controller object, using the
specified controller's constructor function. A new child scope will be
available as an injectable parameter to the controller's constructor
function as $scope.
Read more on controller
As #Sajeetharan said, in angularjs all functions you call need to be declared in controllers, that is how it works
before using ng-click u must place ng-controller in your HTML.
<body ng-app="myApp1" ng-controller="myAppCtrl">
var myApp1 = angular.module('myApp1',[]);
myApp1.controller('myAppCtrl',['$scope',function ($scope) {
$scope.orderByProperty=function(propertyName){
// alert('dsfdf')
return propertyName;
}
}]);
To make it work, 2 places need to change:
Binding orderBy with a ng-model value.
var myApp1 = angular.module('myApp1',[])
myApp1.controller('MyController', ['$scope', function($scope){
$scope. orderByProperty = function(propertyName){
$scope.myorder = propertyName;
}
}])
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="myApp1">
<div ng-controller="MyController">
<div ng-init="users=[{name: 'john', city: 'NY', order: 10},{name: 'james', city: 'washington', order: 20},{name: 'william', city: 'seattle', order: 30}]">
<h2>Customers</h2>
Search Customer: <input type="text" ng-model="searchText" placeholder="search customer here">
<br><br>
<table border="2">
<thead>
<tr>
<th ng-click="orderByProperty('name')">Name</th>
<th ng-click="orderByProperty('city')">City</th>
<th ng-click="orderByProperty('order')">Order</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users | filter : searchText | orderBy : myorder : true">
<td>{{user.name | uppercase}}</td>
<td>{{user.city}}</td>
<td>{{user.order | currency}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

AngularJS - How to get processed HTML output from $compile?

I have the following function which is fetching custom HTML template and passing some values into the scope to generate 'report table'. Because the template is not visible to the user but processed output is directly sent to another function I used $compile function.
It seems that values passed into the $scope are processed correctly but i am not able to get pure HTML result.
I tried to do it by this way:
var templateUrl = $sce.getTrustedResourceUrl('report.html');
$templateRequest(templateUrl).then(function(template) {
$scope.rows = reportData;
var compTest = $compile(template)($scope);
console.log(compTest); //IT RETURNS A LOT OF VALUES BUT NOT HTML OUPUT OF THE PROCESSED TEMPLATE
}, function() {
// An error has occurred
});
Many thanks for any advice.
Results is following:
HTML content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Report</title>
</head>
<body>
<table>
<thead>
<td>
</td>
<td>
Breakfast
</td>
<td>
Lunch
</td>
<td>
Dinner
</td>
<td>
Snack
</td>
</thead>
<tbody>
<tr ng-repeat="row in rows">
<td>TEST</td>
<td>40</td>
<td>20</td>
<td>30</td>
<td>10</td>
</tr>
</tbody>
</table>
</body>
</html>
$compile will return a function which will then be executed by scope which in turn will returns a jQlite wrapped DOM object. So you can use outerHTML to get the Template string
or
You can use $interpolate as shown below
Demo
angular.module('myApp', []);
angular
.module('myApp')
.controller('MyController', MyController);
function MyController($scope, $compile, $interpolate) {
var template = '<a ng-click="handler()">click handler</a>';
this.tmpl = $compile(template)($scope)[0].outerHTML;
this.tmplInt = $interpolate(template)($scope);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyController as MC">
<p><b>using $compile along with outerHTML </b>{{MC.tmpl}}</p>
<p><b>using $interpolate </b>{{MC.tmplInt}}</p>
</div>
</div>

Angular Js - Cannot read property 'push' of undefined - Error

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 = []

Getting and passing MVC Model data to AngularJS controller

I'm pretty new to AngularJS and I'm at a loss here.
Right now my MVC program uses Razor to display all the data in my .mdf database (i.e: #Html.DisplayFor(modelItem => item.LastName) ). However, I want to go mostly Angular. I am trying to use ng-repeat to display all of the Model data, but I am not sure how to pass that Model data to the Angular controller and then use it. I have tried serializing the Model to JSON in my ng-init, but I don't think I'm doing it right (obviously).
Here is my code:
// controller-test.js
var myApp = angular.module('myModule', []);
myApp.controller('myController', function ($scope) {
$scope.init = function (firstname) {
$scope.firstname = firstname;
}
});
<!-- Index.cshtml -->
#model IEnumerable<Test.Models.Employee>
#{
ViewBag.Title = "Index";
}
<div ng-app="myModule">
<div ng-controller="myController" ng-init="init(#Newtonsoft.Json.JsonConvert.SerializeObject(Model))">
<table>
<tr ng-repeat= <!--THIS IS WHERE I'M STUCK -->
</table>
</div>
</div>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/controller-test.js"></script>
#Scripts.Render("~/Scripts/angular.js")
I'm not sure exactly what I should be repeating on to get the FirstName from the serialized Model. I feel like I have all the pieces, but just unsure how to connect them.
If you have the key firstName on your Json object like:
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
}
You can do it in the following way.
On your controller:
myApp.controller('myController', function ($scope) {
$scope.init = function (employees) {
$scope.employees = employees;
}
});
On your view:
<table>
<tr ng-repeat= "employee in employees">
<td>{{ employee.firstName }}<td>
</tr>
</table>
Thank you to darkstalker_010!
What I was confused was with how my Angular controller file interacted with the view. All I had to do was simply treat my angular {{ }} data in my .cshtml file as if I were trying to access the Model data normally (i.e. model.AttributeName)
So here is the updated, working code:
// controller-test.js
var myApp = angular.module('myModule', []);
myApp.controller('myController', function ($scope) {
$scope.init = function (employees) {
$scope.employees= employees;
}
});
<!-- Index.cshtml -->
#model IEnumerable<Test.Models.Employee>
#{
ViewBag.Title = "Index";
}
<div ng-app="myModule">
<div ng-controller="myController" data-ng-init="init(#Newtonsoft.Json.JsonConvert.SerializeObject(Model))">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Title</th>
<th>Department</th>
<th>Email</th>
</tr>
<tr ng-repeat="e in employees">
<td>{{e.FirstName}}</td>
<td>{{e.LastName}}</td>
<td>{{e.Title}}</td>
<td>{{e.Department.DepartmentName}}</td>
<td>{{e.Email}}</td>
</tr>
</table>
</div>
</div>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/controller-test.js"></script>
#Scripts.Render("~/Scripts/angular.js")
Here is what it looks like sans formatting:

how to use modal pop up in angularjs-ui bootstrap

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

Categories

Resources