injecting children with parameter ui-router - angularjs

i want to inject my children view into a web.
I have declared my config:
var states = [
{
name: 'application',
url: '/application',
component: 'application'
},
{
name: 'application.detail',
url: '/:id',
component: 'applicationInfo'
}
];
// Loop over the state definitions and register them
states.forEach(function(state) {
$stateProvider.state(state);
});
i have a button, which tries? to inject view
<button type="button" ui-sref="application.detail({id: application.id})" class="btn btn-sm btn-danger">
<i class="glyphicon glyphicon-info-sign">
</i>
</button>
And a component:
angular.module('crudModule').component('applicationInfo', {
template: '<h1>hellllooooooooo</h1>',
controller: function($stateParams) {
}
});
EDITED:
application component:
angular.module('crudModule').component('application', {
templateUrl: 'applicationModule.html',
controller: function($http, $scope, httpService, $cookies, $log, $document, $dialogs) {
httpService.httpGetRequest('http://localhost:8080/applications').then(function success(response) {
$scope.applications = response.data;
$scope.displayedApplications = [].concat($scope.applications);
})
$scope.deleteApplication = function (id) {
$http({
method: 'DELETE',
url: "http://localhost:8080/application/" + id,
}).then(function success(response) {
httpService.httpGetRequest('http://localhost:8080/applications').then(function success(response) {
$scope.applications = response.data;
$scope.displayedApplications = [].concat($scope.applications);
})})
};
}
});
applicationModule html:
<table st-table="applications" st-safe-src="displayedApplications" class="table table-striped" style="width: auto;">
<thead>
<tr>
<th st-sort='id'>Id</th>
<th st-sort='name'>Name</th>
</thead>
<tbody>
<tr ng-repeat="application in applications">
<td>{{application.id}}</td>
<td>{{application.name}}</td>
<td>More info
<button type="button" ui-sref="application.detail({id: application.id})" class="btn btn-sm btn-danger">
<i class="glyphicon glyphicon-info-sign">
</i>
</button>
</td>
</tr>
</tbody>
</table>
<div class="form-group">
<button class="btn btn-primary" ui-sref="addApplication">Add new</button>
</div>
<div class="form-group">
<button type="button" class="btn btn-default" ng-click="open()">Open me!</button>
</div>
I have included application module:
When i click on the button my url changes to /application/(number) but the view does not change.

You need to have in your application component:
<ui-view></ui-view>
Because the router search this to put the content.
Check the oficial documentation for this:
https://ui-router.github.io/ng1/tutorial/hellogalaxy

Related

Can we use jquery function inside angularjs

I have one table in jquery,In which when I click delete icon I need to display bootstrap modal to perform delete action.I did it using jquery but I dont know to do it in angular..Can anyone give me some suggestions?
<body ng-app="intranet_App">
<div class="container">
<div class="modal" id="deleteProject">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" id="confirmMessage">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="confirmOk">Ok</button>
<button type="button" class="btn btn-default" id="confirmCancel">Cancel</button>
</div>
</div>
</div>
</div>
<div class="col-xs-12 margin20 padding table-responsive">
<table class="col-xs-12 table table-hover table-bordered" id="projectList" ng-controller="myCtrl">
<thead class="colorBlue">
<tr><th>Project Name</th><th>Client</th><th>Client Co-ordinator</th><th>Action</th></tr>
</thead>
<tbody id="projectListTBody" >
<tr ng-repeat="x in projectList | filter:ProjectName">
<td>{{ x.ProjectName}}</td>
<td>{{ x.Client}}</td>
<td>{{ x.OnsiteCoordinator}}</td>
<td>
<i class="fa fa-user-plus fa-2x" ng-click="addResource()"></i>
<i class="fa fa-edit fa-2x" ng-click="editProj(x.Id)"></i>
<i class="fa fa-trash fa-2x" data-toggle="modal" data-target="#myModal" data-dismiss="modal" ng-click="deleteProject(x.Id)"></i>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
<script>
var app = angular
.module("intranet_App", [])
.controller("myCtrl", function ($scope, $http) {
$scope.projDetails = [];
$http.post('/Project/getProjectsList')
.then(function (response) {
console.log(response)
$scope.projectList = response.data;
})
$scope.editProj = function (x) {
$scope.projectDetails(x);
window.location = "/Project/EditProject?id=" + x;
}
$scope.projectDetails = function (x) {
$scope.projDetails.push(x);
$scope.json = angular.toJson($scope.x)
console.log($scope.json)
}
$scope.addResource = function () {
window.location = "/Project/ProjectRes";
}
});
</script>
This is my jquery methods:
function deleteProject(control) {
event.stopPropagation()
id = $(control).closest('tr').attr('id');
confirmDialog("Are you sure do you want to delete this Project?", function () {
removeProject(id)
});
}
function removeProject(elem) {
var updatedBy = $("#userName").text();
var ajxObj = { id: elem};
$.ajax({
type: "POST",
url: "/project/ProjectDelete",
data: JSON.stringify(ajxObj),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$(".success").html("project Deleted successfully!");
$('.success').show();
setTimeout(function () {
$('.success').hide();
}, 1000);
loadProjectsList()
}
});
}
You can use bootstrap angular model popup.
for more information https://angular-ui.github.io/bootstrap/#!#modal

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

has-authority not working on a button

So I used JHipster to generate my app.
I could see the navbar using the has-authority directive to show/hide menus.
Now what I would to do is to use the directive on a button to show it only to users with ROLE_ADMIN
here's the code of the directive
.directive('hasAuthority', ['Principal', function (Principal) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var setVisible = function () {
element.removeClass('hidden');
},
setHidden = function () {
element.addClass('hidden');
},
defineVisibility = function (reset) {
if (reset) {
setVisible();
}
Principal.hasAuthority(authority)
.then(function (result) {
if (result) {
setVisible();
} else {
setHidden();
}
});
},
authority = attrs.hasAuthority.replace(/\s+/g, '');
if (authority.length > 0) {
defineVisibility(true);
scope.$watch(function(scope) {
return Principal.isAuthenticated();
}, function(newValue) {
defineVisibility(true);
});
}
}
};
}]);
here's where it's working
<li ng-class="{active: $state.includes('admin')}" ng-switch-when="true" has-authority="ROLE_ADMIN" class="dropdown pointer">
and here is where I want it to work
<table class="jh-table table table-striped">
<thead>
...
</thead>
<tbody>
<tr
ng-repeat="offeredService in travelRequest.offeredServices track by offeredService.id">
<td><a
ui-sref="offeredServiceType.detail({id:offeredService.offeredServiceType.id})">{{offeredService.offeredServiceType.name}}</a>
</td>
<td>{{offeredService.sellingPrice}}
{{offeredService.currency.symbol}}</td>
<td>{{offeredService.cost}}
{{offeredService.currency.symbol}}</td>
<td>{{offeredService.confirmationDate | date:'medium'}}</td>
<td><a
ui-sref="serviceProvider.detail({id:offeredService.serviceProvider.id})">{{offeredService.serviceProvider.name}}</a>
</td>
<td class="text-right">
<div class="btn-group flex-btn-group-container">
<button type="submit"
ui-sref="offeredService.detail({id:offeredService.id})"
class="btn btn-info btn-sm">
<span class="glyphicon glyphicon-eye-open"></span> <span
class="hidden-xs hidden-sm" translate="entity.action.view"></span>
</button>
<button type="submit"
ui-sref="offeredService.edit({id:offeredService.id})"
class="btn btn-primary btn-sm">
<span class="glyphicon glyphicon-pencil"></span> <span
class="hidden-xs hidden-sm" translate="entity.action.edit"></span>
</button>
<button has-authority="ROLE_USER" type="submit"
ui-sref="offeredService.delete({id:offeredService.id})"
class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-remove-circle"></span> <span
class="hidden-xs hidden-sm" translate="entity.action.delete"></span>
</button>
</div>
</td>
</tr>
</tbody>
</table>
It seems to me that your condition is wrong:
<button has-authority="ROLE_USER" type="submit"
ui-sref="offeredService.delete({id:offeredService.id})"
class="btn btn-danger btn-sm">
An admin user has both authorities ROLE_USER and ROLE_ADMIN.
So in your case the button will always show.
Shouldn't it be like below?
<button has-authority="ROLE_ADMIN" type="submit"

Is it possible to fire ng-click of a button element from a button in another controller?

I want to use angular modal for CRUD operation, so for firing the modal we have button by id modalFire in ng-controller="ModalDemoCtrl" , this is my modal:
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">....</h3>
</div>
<div class="modal-body">
<form id="productForm" novalidate>
<div>
<label for="ProductName"> productName :</label>
<input type="text" name="ProductName" id="ProductName" ng-model="model.ProductName" value="" required />
</div>
<div style="margin:10px">
<label for="Price">price :</label>
<input type="text" name="Price" id="Price" ng-model="model.Price" />
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="Save()" ng-disabled="productForm.$invalid">save</button>
<button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
</div>
</script>
<button type="button" id="modalFire" class="btn btn-default modalBtn" ng-click="open()">UpdateProduct</button>
</div>
and it's controller:
App.controller('ModalDemoCtrl', function ($scope, $modal) {
$scope.open = function (size) {
var modalInstance = $modal.open({
animation: true,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
};
});
App.controller('ModalInstanceCtrl', function ($scope, $modalInstance, $http) {
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
and i have a grid that shows ProductList :
<div ng-controller="ProductController" ng-init="GetAllProducts()">
<div class="row" style="margin-top:90px" ng-show="!ShowGrid">
<article class="widget">
<header class="widget__header">
<div class="widget__title">
<i class="pe-7s-menu"></i><h3>ProductList</h3>
</div>
<div class="widget__config">
<i class="pe-7f-refresh"></i>
<i class="pe-7s-close"></i>
</div>
</header>
<div class="widget__content table-responsive">
<table class="table table-striped media-table">
<thead style="background-color:rgba(33, 25, 36,0.1)">
<tr>
<th style="width:30%">price</th>
<th style="width:30%">productName</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in Products">
<td>{{product.Price}}</td>
<td>{{product.ProductName}}</td>
</tr>
</tbody>
</table>
</div>
</article>
</div>
</div>
so, i want a way to add a button or <a> element for each row in grid that can fire the modal, is there any way?
Unless I misunderstand your question, why not just add the button to your ng-repeat in your table. For example:
<table class="table table-striped media-table">
<thead style="background-color:rgba(33, 25, 36,0.1)">
<tr>
<th>Price</th>
<th>ProductName</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in Products">
<td>{{product.Price}}</td>
<td>{{product.ProductName}}</td>
<td><button ng-click="loadItem(product)>Edit</button></td>
</tr>
</tbody>
</table>
Then inside your controller, just pass the product into your modal load function. For example:
$scope.loadItem = function(product){
var modalInstance = $modal.open({
animation: true,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
product: function () {
return product;
}
}
});
};
See how you can pass the product to the function, and then use resolve to pass the product into the modal. In your modal controller you would attach the product to the $scope, and use it as you would any other view.

ng-click is not working

I'm stuck with this problem for 2 days and I couldn't locate its core so any help on the matter is really appreciated.
I was creating a form that was inline editable with xeditable and the edit(save/cancel) buttons were working as expected but the DELETE button is not calling the given method from the controller. I tried placing it on other parts in the code both as a button and a link and ng-click was not working both ways! I'm quite new at Angular so any debugging tips on how to solve this kinds of problems are welcome! Thanks in advance!
Here is the code from the app file:
var app = angular.module('app', ["Controllers", "xeditable"])
app.run(function (editableOptions) {
editableOptions.theme = 'bs3';
});
Here is the code for the controller (in different .js file from app.js)
angular.module("Controllers", [])
.controller("controller", ["$scope", "$http", function ($scope, $http) {
$scope.users= {};
//get display data
$http.get("/User/All").success(function (data) {
$scope.users= data;
});
//form methods
$scope.editUser = function (data, id) {
edit_data.UserID = id;
$http.post("/User/Edit", edit_data).success(function () {
angular.extend(data, { id: id });
});
};
$scope.deleteUser = function (index, id) {
$http.post("/User/Delete", id).success(function() {
$scope.users.splice(index, 1);
});
};
}]);
Here is the code from the form:
<container ng-app="app" ng-controller="controller">
<table class="table">
<tr>
<th>
Name
</th>
<th>
Surname
</th>
<th></th>
</tr>
<tr ng-repeat="user in users">
<td>
<span editable-text="user.Name" e-name="Name" e-form="rowform" e-required>
{{user.Name}}
</span>
</td>
<td>
<span editable-text="user.Surname" e-name="Surname" e-form="rowform" e-required>
{{user.Surname}}
</span>
</td>
<td style="white-space: nowrap">
<form editable-form name="rowform" onbeforesave="editUser($data, user.UserID)" ng-show="rowform.$visible" class="form-buttons form-inline" shown="inserted == user">
<button type="submit" ng-disabled="rowform.$waiting" class="btn btn-primary">
save
</button>
<button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-default">
cancel
</button>
</form>
<div class="buttons" ng-show="!rowform.$visible">
<button type="button" class="btn btn-primary" ng-click="rowform.$show()">edit</button>
<button type="button" class="btn btn-danger" ng-click="deleteUser($index,user.UserID)">delete</button>
</div>
</td>
</tr>

Resources