angularjs with jquery datatable search button does not work - angularjs

When i try to use jquery datatable with angularjs, search button doesn't work. but if i bind the data using pure asp.net mvc by actionresult method, it works correctly.
I bind the data from user-role.js and i'm using ng-repeat to bind them.
my angularjs version is 1.7.2
jquery.datatble version is 1.10.16
cshtml codes below.
<script type="text/javascript" src="~/Scripts/app/user-role.js"></script>
<div ng-app="userRoleGridApp" ng-controller="userRoleGridCtrl">
<div class="container">
<div class="row">
<div class="col-md-9">
<div class="table-responsive">
<table class="table" id="user-table">
<thead>
<tr>
<th>UserId</th>
<th>User Name</th>
<th>Name Surname</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in Users track by $index">
<th>{{x.UserId}}</th>
<th>{{x.UserName}}</th>
<th>{{x.NameSurname}}</th>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('#user-table').DataTable({
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
//'csvHtml5',
'pdfHtml5'
]
});
});
</script>
Js side
var app = angular.module("userRoleGridApp",
['ngAnimate',
'ngRoute']);
var baseUrl = location.origin;
app.controller("userRoleGridCtrl", function ($scope, $http) {
$scope.Users = {};
initUser();
function initUser() {
$http({
method: "get",
url: baseUrl + "/UserRole/GetUsers"
}).then(function (response) {
$scope.Users = response.data;
}, function () {
alert("Error Occur");
});
}
});

Related

AngularJS - Multiple Modules/Controllers on different pages - only selecting first controller for both pages

I am extremely new to AngularJS and JavaScript in general so any help would be appreciated!
I have two data sources Users and Pets - both are Array objects and I want them to display in a table on different pages of my site. I have an app.module.js which calls the module petsapp or usersapp Currently the controller only being called is the petspp.
I have tried to use $scope but I don't really know what I'm doing!
I currently have set up an app.module.js, which looks like this (but possibly wrong:
(function(){
'use strict';
angular.module('petsapp',[]);
angular.module('usersapp',[]);
})();
another file called **Pets.controller.js:**
(function () {
'use strict';
angular
.module('petsapp')
.controller('PetsController', function ($scope) {
})
PetsController.$inject = ['$http'];
function PetsController($http) {
var vm = this;
vm.pets = [];
vm.getAll = getAll();
vm.deletePet = deletePet();
init();
function init(){
getAll();
}
and a users.controller.js which looks like this:
(function () {
'use strict';
angular
.module('usersapp')
.controller('UsersController', UsersController)
UsersController.$inject = ['$http'];
function UsersController($http) {
var vm = this;
vm.users = [];
vm.getAll = getAll()
vm.delete = deleteUser()
init();
function init(){
getAll();
}
my pets html (working) is:
<!DOCTYPE html>
<script type="text/javascript"src="/static/angular.min.js" th:src="#{/angular.min.js}"></script>
<script type="text/javascript"src="/static/app/app.module.js" th:src="#{/app/app.module.js}"></script>
<script type="text/javascript"src="/static/app/pets.controller.js" th:src="#{/app/pets.controller.js}"></script></head>
<header th:insert="fragments.html :: nav"></header>
<body ng-app="petsapp" ng-controller="PetsController as vm">
<!-- Page content goes here -->
<div>
<div class="row">
<div class="col-lg-offset-2 col-lg-8">
<!-- Display animals in a table -->
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Gender</th>
<th>Breed</th>
<th>Age</th>
<th>OK with Children?</th>
<th style="width: 100px"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="pet in vm.pets">
<td>{{pet.id}}</td>
<td>{{pet.animalName}}</td>
<td>{{pet.animal}}</td>
<td>{{pet.gender}}</td>
<td>{{pet.breed}}</td>
<td>{{pet.age}}</td>
<td>{{pet.compWithChildren}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>.
my users html (not working as it is only pulling the pets.controllers.js) is:
<head th:insert="fragments.html :: headerfiles">
<script type="text/javascript"src="/static/angular.min.js" th:src="#{/angular.min.js}"></script>
<script type="text/javascript"src="/static/app/app.module.js" th:src="#{/app/app.module.js}"></script>
<script type="text/javascript"src="/static/app/users.controller.js" th:src="#{/app/users.controller.js}"></script>
</head>
<header th:insert="fragments.html :: nav"></header>
<body ng-app="usersapp" ng-controller="UsersController as vm">
<!-- Page content goes here -->
<div>
<div class="row">
<div class="col-lg-offset-2 col-lg-8">
<!-- Display animals in a table -->
<table class="table">
<thead>
<tr>
<th>User Name</th>
<th>Roles</th>
<th>Email</th>
<th>Contact Number</th>
<th style="width: 100px"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="userdetail in vm.users">
<td>{{userdetail.username}}</td>
<td>{{userdetail.roles}}</td>
<td>{{userdetail.email}}</td>
<td>{{userdetail.contactNo}}</td>
<td>
<!--Only Admin can delete rows --->
<button class="btn btn-danger" ng-click="vm.deleteUser(userdetail.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html
I think the problem is in the app.module.js file where I've defined two modules?
do I need to combine both controllers into one file? if so how do I implement that?

Selecting default value using ngModel ngRepeat, ngOptions

Hopefully someone can help.
I am developing an application using HTML AngularJs which uses ng-repeat,ng-options and ng-model and populates multiple rows based on the data in the database for a user. Each row has static data coming from DB (returned as object via restAPI) and dynamic select option for user selection. Select option is hardcoded in app.js and linked to model on HTML for DB update upon selection using update button. Each row has its own button and i can see update function is working at row level.
I want to set the default value of the drop down list dynamically as value of an element coming from database. Object is same as one being used to populate rows with static data .
Code is in the fiddle at https://jsfiddle.net/6j88L61y/4/
HTML below
<body>
<h1 align="center">User Tracker</h1>
<div ng-controller="MainController as main">
<div>
<p>Please Enter ID </p>
<p>
<input type="text" ng-model="main.model.userName"></input>
<button ng-click="main.model.getOrgList()">List State List</button>
</p>
</div>
<hr ng-show="main.model.formSubmitted"></hr>
<div>
<table class="table table-bordered" border="1">
<thead>
<tr>
<th>ID</th>
<th>User Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="org in main.model.orgList" id="{{org.id}}">
<td>{{org.id}}</td>
<td align="center">{{org.user}}</td>
<td align="center">
<select ng-model="main.model.selectedRecord.appCurrentStateSelected[$index]" ng-options="option.value as option.value for option in main.model.appCurrentStateList" ></select>
</td>
<td>
<button ng-click="main.model.updateAppDetailsList({id:org.id,userName:org.name,appCrntState:main.model.selectedRecord.appCurrentStateSelected})">Update</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
JS
"use strict";
angular.module('myApp',[]);
angular.module('myApp').service('AppModel', function( $http) {
this.userId='';
this.userName ="";
this.formSubmitted="";
this. selectedRecord ={appCurrentStateSelected:''};
this.appCurrentStateList =[{name: 'New',value:'New',id:1}, {name: 'InUse',value:'InUse',id:2},{name: 'Inactive',value:'Inactive',id:3},{name: 'Deleted',value:'Deleted',id:4}];
this.submittedAppDetailsList=[];
console.log(' json sample:'+this.submittedAppDetailsList);
var path = 'home';
var currentProtocol = location.protocol;
var host =location.host;
var apiHost = currentProtocol+'//'+host+'/api/';
console.log('API url is : ' +apiHost);
// Get method
this.getOrgList = function() {
var path = 'home/userid';
console.log(this.userName);
console.log(this.selectedRecord);
$http.get(apiHost+path+'/'+this.userName+'/')
.then(function(response) {
this.orgList =response.data;
this.formSubmitted = true;
console.log(response.data);
}.bind(this),
function(response) {
console.log(response.data);
});
}
// Post method
this.updateAppDetailsList = function(appdetailsList) {
var path = 'home/update';
console.log(this.selectedRecord);
$http.post(apiHost+'home/update/',appdetailsList)
.then(function(response) {
this.submittedAppDetailsList.push(response.data);
this.formSubmitted = false;
console.log(response.data);
}.bind(this),
function(response) {
console.log('Error : '+response.data);
});
}
});
angular.module('myApp').controller('MainController', ['AppModel', function (AppModel) {
this.model = AppModel;
}]);

bootstrap-table not rendering upon updating model in Angular

Hi I am not able to render table using bootstrap-table and angular. here is my code, I think I need to call bootstrap-table init method in angular ajax call. Can some one guide me on how to do this..?
angular
.module('reports')
.controller(
'ReportCtrl',
[
'$scope',
'$http',
'ngProgress',
function($scope, $http, ngProgress) {
var vm = this;
vm.mdp = {};
vm.mdp.data = [];
vm.mdp.columns = [];
$scope.submit = function() {
var report = $scope.tab;
$http.post('/reports/cmd/getData', {
report : report,
date : createdAfter
}).success(function(data) {
vm.mdp.data = data;
$.each(data[0], function(key, value){
vm.mdp.columns.push(key);
});
}).error(function(error) {
alert(error);
});
};
} ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mdp" class="panel" ng-controller="ReportCtrl as report" ng-show="panel.isSelected('mdp')">
<table data-toggle="table" data-show-columns="true" data-search="true" data-show-export="true" data-pagination="true" data-height="299">
<thead>
<tr>
<th ng-repeat="c in report.mdp.columns" data-field= {{c}} >{{ c }}</th>
</tr>
</thead>
<tr ng-repeat="r in report.mdp.data">
<td ng-repeat="c in report.mdp.columns">{{ r[c] }}</td>
</tr>
</table>
</div>
Integrating Bootstrap Table with Angular is solved here:
https://github.com/wenzhixin/bootstrap-table/issues/165
https://github.com/AkramKamal/bootstrap-table-examples/tree/master/integrate
I have some minor changes in my implementation of this solution which I will upload to Github / JSFiddle shortly. But the links above will allow you to get going.

Breaking the ice on angular

I have a view:
<div id="productList" ng-controller="ProductController">
<table class="table table-bordered">
<thead>
<tr>
<th></th>
<th width="100%">Item ID</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in productItems">
<td><input type="checkbox" /></td>
<td><% item.ID %></td>
</tr>
</tbody>
</table>
</div>
I have a controller:
var TestApp = angular.module('TestApp', [], function( $interpolateProvider ) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
TestApp.controller('ProductController', function ( $scope ) {
ProductRepository.GetPaginatedProducts();
$scope.productItems = ProductRepository.Model;
});
I have a model:
var ProductRepository = function ()
{
return {
Model: null,
GetPaginatedProducts: function()
{
$.ajax( {
"url": Test.URL + "/json/products/paginated",
"dataType": "json",
"method": "post",
"success": function( data )
{
ProductRepository.Model = data;
}
} );
},
}
}
When the ajax finished, it updates the ProductRepository.Model data variable which I want the angular controller scope.productItems to work off of.
This is my first time using angular and i think I've missed the point,
Why is the table not updating with the information?
Please see here for sample ajax call http://plnkr.co/edit/5CiC8MWiwo010nwu32he?p=preview
var TestApp = angular.module('plunker', []);
TestApp.factory('ProductRepository', function($http, $q) {
var Model = [];
return {
Model: Model,
GetPaginatedProducts: function() {
var deferred = $q.defer();
$http.get('paginated.json').then(
//sucess
function(result) {
deferred.resolve(result.data)
}
//error
, function() {});
return deferred.promise;
}
};
})
TestApp.controller('ProductController', function($scope, ProductRepository) {
$scope.productItems = [];
ProductRepository.GetPaginatedProducts().then(function(data) {
//success
$scope.productItems = data;
},
//error
function() {
alert("can't get data");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="plunker">
<div id="productList" ng-controller="ProductController">
<table class="table table-bordered">
<thead>
<tr>
<th></th>
<th width="100%">Item ID</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in productItems">
<td>
<input type="checkbox" />
</td>
<td>{{item.ID}}</td>
</tr>
</tbody>
</table>
</div>
</div>
As #tymeJV stated in the comment, you should use $http or $resource (or restangular) to perform the data access. If you are updating values outside of Angular's framework, it has no way of knowing that data has changed. By using something like $http or $resource, Angular is aware when an event has occurred that can change values and automatically checks for updates.
Alternately, you could manually issues an $apply() to essentially handle the digest update manually (ensuring Angular goes through a digest cycle when you've changed values outside of Angular). Take a look at the documentation on $apply() at https://docs.angularjs.org/api/ng/type/$rootScope.Scope .
However, your best bet is to use the Angular approach in the first place and avoid using jQuery for this.

AngularJS - HTML not updating on variable change

I am trying to learn AngularJS and i am making a test app.
I have a table that gets populated with data returned from a WebService (list of publishers) via $http.get().
When the user clicks a row (publisher) i want to fill a second table with the list of employees of the selected publisher. By using the F12 tools (Network+Console) i see that the data is returned but the second table is not filled/updated.
html
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css" type="text/css" />
<script src=""></script>
<script src="js/angular.js"></script>
<script src="js/scripts.js"></script>
<script src="js/app.js"></script>
<title>My SPA</title>
</head>
<body>
<header>
<h1 id="page-title">Header</h1>
<nav>
<ul>
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
<li>Menu 4</li>
</ul>
</nav>
</header>
<div ng-controller='PublishersController' class="table-wrapper">
<table class="data-table" />
<thead>
<tr>
<th ng-repeat="(key,val) in publishers[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='pub in publishers' ng-click='getPublishersEmployees(pub.pub_id)'>
<td ng-repeat='(key,val) in pub'>{{val}}</td>
</tr>
</tbody>
</table>
</div>
<div ng-controller='PublishersController' class="table-wrapper">
<table class="data-table" />
<thead>
<tr>
<th ng-repeat="(key,val) in employees[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='employee in employees'>
<td ng-repeat='(key,val) in employee'>{{val}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
JS
var urlBase = "http://localhost:2041";
var app = angular.module('myApp', []);
app.factory('myFactory', ['$http', function ($http) {
var webAPI = '/api/query';
var webService = urlBase + webAPI;
var myFactory = {};
myFactory.getCategories = function () {
return $http.get(webService + '/getCategories');
};
myFactory.getCategorySalesByMonth = function (id) {
return $http.get(webService + '/getCategorySalesByMonth/' + id);
};
myFactory.getPublishers = function () {
return $http.get(webService + '/getPublishers');
};
myFactory.getPublishersEmployees = function (id) {
return $http.get(webService + '/getPublishersEmployees/' + id);
};
return myFactory;
}]);
app.controller('PublishersController', ['$scope', 'myFactory',
function ($scope, myFactory) {
$scope.status;
$scope.publishers;
$scope.employees;
getPublishers();
function getPublishers() {
myFactory.getPublishers()
.success(function (publishers) {
$scope.publishers = publishers;
})
.error(function (error) {
$scope.status = 'Unable to load publishers data: ' + error.message;
});
}
$scope.getPublishersEmployees = function (id) {
myFactory.getPublishersEmployees(id)
.success(function (employees) {
$scope.employees = employees;
console.log($scope.employees);
})
.error(function (error) {
$scope.status = 'Error retrieving employees! ' + error.message;
});
};
}]);
What am i doing wrong?
The problem is you use separate controllers for PublishersController and EmployeesController. Angular will create separate scopes for your controllers. Therefore, when you assign $scope.employees = employees in your PublishersController, it does not reflect on the scope created by EmployeesController
Try:
<div ng-controller='PublishersController' class="table-wrapper">
<table class="data-table" />
<thead>
<tr>
<th ng-repeat="(key,val) in publishers[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='pub in publishers' ng-click='getPublishersEmployees(pub.pub_id)'>
<td ng-repeat='(key,val) in pub'>{{val}}</td>
</tr>
</tbody>
</table>
<table class="data-table" />
<thead>
<tr>
<th ng-repeat="(key,val) in employees[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='employee in employees'>
<td ng-repeat='(key,val) in employee'>{{val}}</td>
</tr>
</tbody>
</table>
</div>
That solution above is just to point out your problem. I don't know your application design, you may not follow this solution but restructure your code to best fit your application design (like storing the employees in a shared service,...).
Here I propose another solution but I'm not sure if it fits with your application. You just use your original HTML code with PublishersController and EmployeesController. In your PublishersController, your could broadcast an event from rootScope:
.success(function (employees) {
$rootScope.$broadcast("employeeLoaded",employees);
})
Don't forget to inject $rootScope to your PublishersController:
app.controller('PublishersController', ['$scope', 'myFactory','$rootScope',
function ($scope, myFactory,$rootScope)
In your EmployeesController, you could subscribe to this event:
$scope.$on("employeeLoaded",function (event,employees){
$scope.employees = employees;
});
For more information about event in angular, check out Working with $scope.$emit and $scope.$on

Resources