How to fire a function in AngularJS controller after HTML loaded - angularjs

I am working on my angularJS tutorila project.
I need to fire function in controller when the HTML page loaded.
But I don't know how to implement it.
Here is my view:
<div class="row" ng-controller="SensorController as vm">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading clearfix">
<h1 class="panel-title">Sensor Response</h1>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-5">
<table class='table borderless table-striped tableContentLeftAlign table-striped-column table-header-color'>
<thead>
<tr>
<th class="col-md-1">Data</th>
<th class="col-md-3">Data name</th>
</tr>
</thead>
<tbody>
<tr>
<td class="col-md-1">MessageNumber:</td>
<td class="col-md-3">{{vm.sensorData.MessageNumber || 'Empty' }}</td>
<tr>
</tr>
<td class="col-md-1">MessageID:</td>
<td class="col-md-3">{{vm.sensorData.MessageID || 'Empty'}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Here is controller:
(function () {
"use strict";
angular.module("sensorManagement").controller("SensorController",
["SensorResource",
"$location",
"toaster",
SensorController]);
function SensorController(SensorResource, $location, toaster) {
var vm = this;
function foo(){
SensorResource.get({ id: "12345678" }, function (data) {
vm.sensorData = data;
},
function (responce) {
});
};
vm.SaveData = function () {
if (!vm.sensorData) {
alert("No data!");
return;
}
SensorResource.save(vm.sensorData, function (data) {
alert("Saved");
},
function (error) {
//Here to implement exception!!!
});
};
vm.GetLog = function () {
SensorResource.query(function (data) {
vm.log = data;
}, function (error) {
//Here to implement exception!!!
});
};
}
})();
I need the function foo() in controller SensorController to be fired after HTML is loaded.
Any idea how can I implement it?

Try something like this:
$scope.$on('$viewContentLoaded', function(){
// TODO logic
});
This code is waiting to event viewContentLoaded. This handler should acts when the page has been loaded.
I hope you work.

Related

How could I update a Datatable in modal using AngularJS

I have been stuck in something simple that I think I haven't solved yet because of a lack of experience. Here is the catch I have a very simple controller which load the data from a service when I first Load the modal but once I tried to use the CRUD operations (hopefully working!!) the datatable doesn't update. I will share the code. Thanks of all.
I need that after insert, for example, the datatable update meaning rerender the current list of elements.
Call of the Modal
vm.openBooksModal = function (authorId) {
var modalInstance = $uibModal.open({
templateUrl: '/app/book/index.html,
controller: 'BooksController',
size: '',
resolve: {
authorId: function () {
return authorId;
}
}
});
Modal Controller
(function () {
'use strict';
angular.module('bookApp').controller('BooksController', BooksController);
BooksController.$inject = ['$uibModalInstance', '$scope', 'authorId', 'bookService', 'DTOptionsBuilder', 'DTColumnDefBuilder',
'DTColumnBuilder', 'dtUtils','alertService'];
function NotesController($uibModalInstance, $scope, authorId, bookService, DTOptionsBuilder, DTColumnDefBuilder,
DTColumnBuilder, dtUtils, alertService) {
$scope.authorId= authorId;
$scope.book= {
id: 0,
title:''
};
//if (angular.isDefined())
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
}
$scope.dtBooksColumnDefs = [
DTColumnDefBuilder.newColumnDef(0).notSortable()
];
$scope.dtBooksOptions = DTOptionsBuilder
.newOptions()
.withOption('bFilter', false)
.withOption('order', [[2, 'desc']])
.withOption('aaSorting', [])
.withOption('lengthMenu', [[5, 10, 25, 50], [5, 10, 25, 50]]);
$scope.dtBooksInstance = {};
$scope.LoadData = LoadData();
function LoadData(){
return bookService.getBook($scope.authorId).$promise
.then(getBookCompleted, handleError);
}
$scope.save = function (newTitle) {
$scope.book.title= newTitle;
bookService.saveBook($scope.book.id, $scope.authorId, $scope.book.title).$promise
.then(saveBookCompleted, handleError);
LoadData();
}
$scope.editBook= function( book){
$scope.book= book;
$scope.newTitle= book.title;
}
$scope.deleteBook = function( book){
bookService.deleteBook(book.id).$promise
.then(saveBookCompleted, handleError);
}
//private methods
function getBookCompleted(data) {
$scope.leadBookList = data;
debugger;
if (angular.isDefined($scope.dtBookInstance.rerender)) {
$scope.dtBooksInstance.rerender();
}
$scope.book= { };
$scope.newTitle = '';
}
function saveBookCompleted() {
bookService.getBook($scope.authorId).$promise
.then(getBookCompleted, handleError);
}
function handleError(response) {
alertService.error("Error trying to add a Note. Please try again later or contact IT.");
}
}
})();
HTML TEMPLATE
<div class="modal-header">
<h3 class="modal-title">Books</h3>
</div>
<div class="modal-body">
<div class="book-container">
<div class="head">
</div>
<div class="book">
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<label class="control-label">{{headerLabel}}</label>
<textarea id="newTitle" class="comment-textarea" data-ng-model="newTitle" rows="8" cols="90"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<table id="tblBooks" datatable="ng" class="table table-striped table-bordered font-xs"
dt-options="dtBookOptions" dt-column-defs="dtBookColumnDefs" >
<thead>
<tr>
<th></th>
<th></th>
<th>Title</th>
<th>Created By</th>
<th>Created Date</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="book in BookList">
<td>
<button class="btn btn-sm btn-warning" ng-click="editBook(book)">
<i class="fa fa-pencil"></i>
</button>
</td>
<td>
<button class="btn btn-sm btn-danger" ng-click="deleteBook(book)">
<i class="fa fa-trash-o"></i>
</button>
</td>
<td>{{book.title}}</td>
<td>{{book.createdBy}}</td>
<td>{{book.createdDate | date:'MM/dd/yyyy HH:mm:ss'}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer margin-top-0">
<button class="btn btn-primary" ng-click="save(newBook)" data-ng-disabled="newTitle === ''">Save</button>
<button class="btn btn-primary" ng-click="cancel()">Close</button>
</div>
Thanks
You're calling getBookCompleted twice. First after save in the saveBookCompleted function and second in the loaddata function
$scope.save = function (newTitle) {
$scope.book.title= newTitle;
bookService.saveBook($scope.book.id, $scope.authorId, $scope.book.title).$promise
.then(saveBookCompleted, handleError);
// remove this line since you're already call saveBookCompleted
//LoadData();
}

How to prevent destroy data from DataTable with Angular

I'm try to implement DataTables with Angular, I'm googled and some many solutions is creating directives, its ok but is very old only "normal" way draw a DataTable, the problem is sorting or typing into search box my data is lost!! E.g:
And my code:
View
var myApp = angular.module('myApp', ['ngRoute','ui.utils']);
myApp.controller("CompanyController", function ($scope, $window, CompanyService) {
$scope.Companies = [];
$scope.Company = {};
$scope.dataTableOpt = {
//custom datatable options
"aLengthMenu": [[10, 50, 100, -1], [10, 50, 100, 'All']],
};
$scope.$watch("data", function (value) {
console.log("Data changed, refresh table:");
var val = value || null;
if (val) {
}
});
$scope.InitializeIndexView = function () {
var getAllProcess = CompanyService.GetAllCompanies();
getAllProcess.then(function (response) {
//console.log(response.data)
$scope.Companies = response.data;
},
function (response) {
console.log(response);
})
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<table id="company-table" class="table table-striped table-bordered" ui-jq="DataTable" ui-options="dataTableOpt">
<thead>
<tr>
<th>Id</th>
<th>Register time</th>
<th>Short Name</th>
<th>Long Name</th>
<th>Status</th>
<th>Owner Client</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in Companies">
<td>{{item._id}}</td>
<td>{{item.RegisterTime}}</td>
<td>{{item.LongName}}</td>
<td>{{item.ShortName}}</td>
<td>{{item.CompanyStatus}}</td>
<td>{{item.OwnerClient}}</td>
<td>Edit | Delete</td>
</tr>
</tbody>
</table>
Edit 1:
I follow these snippet and works fine because data is static: http://codepen.io/kalaiselvan/pen/RRBzda
Angular Js
var app = angular.module('myApp', ['datatables']);
app.controller("myCtrl", function ($scope, $http, DTOptionsBuilder, DTColumnBuilder) {
$scope.isDisabledupdate = true;
$scope.GetAllData = function () {
$http({
method: "get",
url: "http://localhost:8200/Employee/Get_AllEmployee"
}).then(function (response) {
$scope.employees = response.data;
}, function () {
alert("Error Occur");
})
};
$scope.vm = {};
$scope.vm.dtOptions = DTOptionsBuilder.newOptions()
.withOption('order', [0, 'asc']);
View Page
<div class="panel-body" ng-init="GetAllData()">
<div class="table-responsive">
<table class="table table-striped table-bordered" datatable="ng" dt-options="vm.dtOptions">
<thead>
<tr>
<th>S.no</th>
<th>
ID
</th>
<th>
City Name
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="Emp in employees">
<td>{{$index+1}}</td>
<td>
{{Emp.CId}}
</td>
<td>
{{Emp.CityName}}
</td>
<td>
<button type="button" class="btn btn-default btn" ng-click="getCustomer(Emp)"><i class="glyphicon glyphicon-pencil"></i></button>
<button type="button" class="btn btn-default btn" ng-click="deleteemp(Emp)"><i class="glyphicon glyphicon-trash"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-datatables.min.js"></script>
<script src="~/Scripts/jquery.dataTables.min.js"></script>
<script src='https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js'></script>
I hope this code will help you....

AngularJS UI-Router loaded page control doesn't working without reload page

I'm using UI-Router for routing.
When i load a .html page using this code :
$stateProvider.state("admin.cabletv.all-invoice", {
url: "/all-invoice",
templateUrl: "app/invoice/invoice-list.html",
params: {
'type': '1'
},
cache: false
});
invoice-list.html
<div class="panel panel-primary" ng-controller="pqsInvoiceListController as model">
<div class="panel-heading">
<div class="row">
<div class="col-sm-2">{{model.pageTitle}}</div>
<div class="col-sm-2 col-sm-offset-8">
<button class="btn btn-default" ng-click="model.printInvoice()">Print</button>
</div>
</div>
</div>
<div class="panel-body">
<div style="overflow-x: auto">
<table class="table table-bordered">
<thead>
<tr>
<th><input type="checkbox" ng-model="model.selectedAll" ng-change="model.checkAll()" autocomplete="off" /></th>
<th>In. no</th>
<th>Type</th>
<th>Client</th>
<th>Client Id</th>
<th>Mobile No</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="invoice in model.invoices">
<td><input type="checkbox" ng-model="model.idList[invoice.id].isSelected"/></td>
<td>{{invoice.id}}</td>
<td>{{invoice.invoiceType | pqsInvoiceType}}</td>
<td>{{invoice.connection.client.name}}</td>
<td>{{invoice.connection.client.id}}</td>
<td>{{invoice.connection.client.mobileNumber1}}</td>
</tr>
<tr ng-if="model.invoices.length">
<td colspan="12">Total</td>
<td>{{model.totalAmount}}</td>
<td colspan="4"></td>
</tr>
</tbody>
</table>
</div>
</div>
Part of my controller
(function (module) {
var pqsInvoiceListController = function () {
var vm = this;
vm.idList = {};
var buildIdList = function(invoices) {
angular.forEach(invoices, function (invoice) {
vm.idList[invoice.id] = {isSelected : false};
});
};
vm.checkAll = function () {
vm.selectedAll = !!vm.selectedAll;
angular.forEach(vm.idList, function (id) {
id.isSelected = vm.selectedAll;
});
};
};
module.controller("pqsInvoiceListController", pqsInvoiceListController);
}(angular.module("pqs.ui")));
invoice-list.html page is loaded, but the control(checkbox) in this page is not working. When i click checkbox it is not working. If i reload page using F5 then it works fine. How can i solve this problem without reloading page.

Angular doesn't refresh the table after adding new item

When i get GetAll(); angular function to refresh the table it called Because i get the alert message but it doesn't refresh the table.
I am new in AngularJS and i don't know how to solve that problem
Please help me
Here is my code:
[HttpGet]
public JsonResult GetAllContinents()
{
MyDatabaseEntities db = new MyDatabaseEntities();
var Result = (from con in db.Continents select new { ContinentId = con.ContinentId, ContinentName = con.ContinentName.Trim() }).ToList();
return Json(Result, JsonRequestBehavior.AllowGet);
}
HTML:
<div data-ng-controller="myCntrl">
<div class="col-md-12">
<table class="table table-bordered table-hover" style="width:800px">
<thead>
<tr>
<th><b></b>ID<b></b></th>
<th>continent Name</th>
<th>Modify</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="con in ContinentsList">
<td>{{con.ContinentId}}</td>
<td>{{con.ContinentName}}</td>
<td>
<button class="btn btn-md glyphicon glyphicon-trash"
title="Click here to delete record" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div data-ng-controller="myCntrl">
Enter Continent Name: <input type="text" ng-model="Continent.ContinentName" />
<input type="button" value="Add" ng-click="AddContinent()" />
</div>
AngularJs:
app.controller("myCntrl", function ($scope, $http, angularService) {
$scope.GetAll = function () {
$scope.ContinentsList = [];
$http.get('/Home/GetAllContinents')
.success(function (data) {
$scope.ContinentsList = data;
alert('Done!')
})
.error(function (msg) {
alert(msg);
})
};
$scope.GetAll();
$scope.AddContinent = function () {
$http.post('/Home/AddContinent', { Con: $scope.Continent })
.success(function (data) {
$scope.clear();
$scope.GetAll();
})
.error(function (msg) {
alert(msg)
})
};`enter code here`
Thank you in advance
You have to define the Continental ist ouside the function scope.
$scope.ContinentsList = [];
function getAll () {
$http.get('/Home/GetAllContinents')
.success(function (data) {
$scope.ContinentsList = data;
alert('Done!')
})
.error(function (msg) {
alert(msg);
})
};
Remove ng-controller from :
<div data-ng-controller="myCntrl">
Enter Continent Name: <input type="text" ng-model="Continent.ContinentName" />
<input type="button" value="Add" ng-click="AddContinent()" />
</div>
Now you have two scope and two lists of content and it's problem. In one scope you have a list that you show on view and in second scope you add elements and try refresh lists.
This is working code:
<div data-ng-controller="myCntrl">
<div class="col-md-12">
<table class="table table-bordered table-hover" style="width:800px">
<thead>
<tr>
<th><b></b>ID<b></b></th>
<th>continent Name</th>
<th>Modify</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="con in ContinentsList">
<td>{{con.ContinentId}}</td>
<td>{{con.ContinentName}}</td>
<td>
<button class="btn btn-md glyphicon glyphicon-trash"
title="Click here to delete record" />
</td>
</tr>
</tbody>
</table>
</div>
Enter Continent Name: <input type="text" ng-model="Continent.ContinentName" />
<input type="button" value="Add" ng-click="AddContinent()" />
</div>

AngularJS - hide table template until form submitted using custom directive

I have the following code that makes a PUT request and displays the
modified data returned from the server in a table. Right now, when
the page is loaded, an empty table is displayed until the button is clicked.
What I require is that the table be hidden until the button is clicked. How
do I accomplish this?
<div ng-app="myApp" ng-controller="formController">
<script type="text/ng-template" id="tableTemplate.html">
<table>
<thead>
<tr>
<th>id</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in names">
<td>{{ x.id }}</td>
<td>{{ x.email }}</td>
<tr>
</tbody>
</table>
</script>
<form ng-submit="processForm()">id :
<input type="text" name="id" ng-model="formData.id">email :
<input type="email" name="email" ng-model="formData.email">
<input type="submit" value="go">
</form>
<div my-directive></div>
</div>
<script>
var app = angular.module('myApp',[]);
app.directive('myDirective', function() {
return {
replace: true,
restrict: 'EA',
templateUrl: 'tableTemplate.html'
}
});
app.controller("formController", function($scope,$http) {
$scope.formData = {};
$scope.processForm = function(){
// PUT /users/id
var url = 'http://www.example.com/users/' + $scope.formData.id;
var data = '{"email":"' + $scope.formData.email}';
$http({method: 'PUT', url: url, data: data}).success(function(response){
$scope.names = response;
});
}
});
</script>
In the HTML:
<table ng-show="formSubmitted">
In the controller $http success() function:
$scope.formSubmitted = true;

Resources