Angularjs error when i try remove button and append a new? - angularjs

I have follow.js:
'user strict';
var SaurioApp = angular.module('SaurioApp', []);
SaurioApp.controller('SearchCtrl', function($scope, $http){
$scope.followUser = function(user_id,follow_to_id){
$http.get('ajax/follow', {
params: {user_id: user_id,follow_to_id: follow_to_id}
}).success(function(data){
$scope.unfollow = '<button class="btn btn-danger" ng- click="followUser({{Auth::user()->id}},{{$user->id}})">Seguir</button>';
});
}
});
and the view in blade
<div class="row" ng-app="SaurioApp">
<div class="col-xs-12 col-sm-12 col-md-12" >
<p ng-controller="SearchCtrl" >
#{{ unfollow }}
<button class="btn btn-primary" ng-click="followUser({{Auth::user()->id}},{{$user->id}})">Follow</button>
</p>
</div>
</div>
The insert is successful, but I can't delete the "Follow" button and append the new one: "Unfollow." How can I make this work?

<div class="row" ng-app="SaurioApp">
<div class="col-xs-12 col-sm-12 col-md-12" >
<p ng-controller="SearchCtrl" >
<button ng-show='unfollow' class="btn btn-danger" ng-click="followUser({{Auth::user()->id}},{{$user->id}})">Seguir</button>
<button ng-hide='unfollow' class="btn btn-primary" ng-click="followUser({{Auth::user()->id}},{{$user->id}})">Follow</button>
</p>
</div>
</div>
Similar to what #redoc says but with two buttons, one for unfollow and one for follow
SaurioApp.controller('SearchCtrl', function($scope, $http){
$scope.followUser = function(user_id,follow_to_id){
$http.get('ajax/follow', {
params: {user_id: user_id,follow_to_id: follow_to_id}
}).success(function(data){
$scope.unfollow = true;
});
}
});

It seems as if the only changes needed to be made are the CSS class and button text so in this case instead of trying to send HTMl code through the scope just send a variable and use ng-class to make the switch. Something like this:
'user strict';
var SaurioApp = angular.module('SaurioApp', []);
SaurioApp.controller('SearchCtrl', function($scope, $http){
$scope.followUser = function(user_id,follow_to_id){
$scope.unfollow=false;
$http.get('ajax/follow', {
params: {user_id: user_id,follow_to_id: follow_to_id}
}).success(function(data){
$scope.unfollow = true;
});
}
});
<div class="row" ng-app="SaurioApp">
<div class="col-xs-12 col-sm-12 col-md-12" >
<p ng-controller="SearchCtrl" >
#{{ unfollow }}
<button ng-class="{btn-danger: unfollow=false }" ng-click="followUser({{Auth::user()->id}},{{$user->id}})">Follow</button>
</p>
</div>
</div>
You can also change the button text dynamically with something like this:
<button value="{{(unfollow=false)? 'Follow' : 'Seguir'}}" ng-class="{btn-danger: unfollow=false }" ng-click="followUser({{Auth::user()->id}},{{$user->id}})"></button>
I guess the point being there is no need to actually recreate the HTML code just change the elements.

Related

How can I make ng-click work in AngularJs

I added some ng-click events for buttons but when I try to click buttons, test() function won't fire. I did everything to fix that but I couldn't.
<div ng-controller="bilgiyarismasiCtrl" ng-repeat="x in sorular">
<div class="row text-center" style="margin: 50px 250px 50px 250px;">
<div class="col-md-12" style="padding:90px; background-color:gray; color:white;">
{{ x.SORU_ICERIGI }}
</div>
<div class="col-md-6" style="padding:50px; background-color:white;">
<button ng-click="test()" class="btn btn-primary btn-lg">{{ x.A_SIKKI }}</button>
</div>
<div class="col-md-6" style="padding:50px; background-color:white;">
<button ng-click="test()" class="btn btn-primary btn-lg">{{ x.B_SIKKI}}</button>
</div>
</div>
<br /><br /><br />
</div>
Angular code:
var app = angular.module("module", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "bilgiyarismasi.html",
controller: "bilgiyarismasiCtrl"
});
});
app.controller("bilgiyarismasiCtrl", function ($scope, $http) {
$http.get("http://localhost:53438/api/BilgiYarismasi/GetSorular")
.then(function (response) {
$scope.sorular = response.data;
});
$scope.test = function () {
console.log(1)
}
});
FYI, Your code above is not invoking controller, due to this you are not able get output by clicking on any of your buttons.
Use below code :
var ngApp = angular.module('app', []);
ngApp.controller('bilgiyarismasiCtrl',function($scope, $http){
$scope.sorular = [];
/* $http.get("http://localhost:53438/api/BilgiYarismasi/GetSorular")
.then(function (response) {
$scope.sorular = response.data;
}); */
$scope.test = function () {
console.log('test')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="bilgiyarismasiCtrl">
<div >
<div class="row text-center" style="margin: 50px 250px 50px 250px;">
<div class="col-md-12" style="padding:90px; background-color:gray; color:white;">
{{ x.SORU_ICERIGI }}
</div>
<div class="col-md-6" style="padding:50px; background-color:white;">
<button ng-click="test()" class="btn btn-primary btn-lg">{{ 'x.A_SIKKI' }}</button>
</div>
<div class="col-md-6" style="padding:50px; background-color:white;">
<button ng-click="test()" class="btn btn-primary btn-lg">{{' x.B_SIKKI'}}</button>
</div>
</div>
<br /><br /><br />
</div>
</div>
</div>
You have not included ng-app in your template file.
I have created a demo, can you please have a look.
Hope this helps you.

How to invoke a modal from a controller in angularjs / ui-bootstrap?

I am trying to display a modal (Note view) from a controller (Details controller). I have separate controllers tied to each view.
The Details view has a list of radio buttons and upon selecting a radio button, it needs to display a modal with some data and OK and Cancel buttons.
Also, I need to deselect the radio button which is selected in Details view when cancel button is clicked on the modal.
How can I wire up all this? I am trying the below code and I get internal server error upon calling note modal from Details controller.
I copied some parts from my code to show what I am trying.
Thanks for any suggestions.
Details view:
<div class="list-group-item" ng-repeat="cpo in details.detailoptions">
<div class="row">
<h4><input type="radio" name="optRadio" ng-model="$parent.selectedOption"
ng-value="{{o}}" ng-change="optionSelected()"
ng-disabled="disableOptions" /></h4>
</div>
</div>
Details controller:
appControllers.controller('detailsCtrl', ['$scope', '$uibModal',
function ($scope, $uibModal) {
$scope.selectedOption;
$scope.optionSelected = function () {
//call note modal
$uibModal.open({
templateUrl: 'notePanel',
controller: 'noteCtrl',
scope: $scope
});
}
}
]);
Note view:
<script type="text/ng-template" id="notePanel" ng-controller="noteCtrl">
<div id="noteModal" class="modal fade">
<div class="modal-dialog">
<div class="form-group">
<div class="row">
<div class="col-md-offset-2 col-md-8">
<h4>{{Note.Note1}}</h4>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-offset-1 col-md-10">
{{Note.Note2}}
</div>
</div>
</div>
<div class="panel-footer clearfix">
<div class="row row-centered">
<div class="col-xs-3 col-thin col-centered">
<button type="submit" class="btn btn-primary btn-block" data-dismiss="modal" ng-click="OK()"><span class="glyphicon glyphicon-ok"></span> Agree</button>
</div>
<div class="col-xs-3 col-thin col-centered">
<button type="button" class="btn btn-default btn-block" ng-click="Cancel()"><span class="glyphicon glyphicon-remove"></span> Disagree</button>
</div>
</div>
</div>
</div>
</div>
</div>
</script>
Note controller:
appControllers.controller('noteCtrl', ['$scope', 'dataService',
function ($scope, service) {
$scope.Note;
$scope.OK = function () {
//close modal
}
$scope.Cancel = function () {
//deselect the option selected in Details view.
}
function init() {
service.getNote($scope.optionSelected, function (data) {
if (data) {
$scope.Note = data;
}
else {
console.log('Error getting note file');
//show error dialog
}
});
}
init();
}
]);

AngularStrap - modal doesn't hide

I have modal invoked with just HTML tags:
<button class="btn btn-xs stop" data-template-url="template/modal.html"
bs-modal="modal">
</button>
but after that I can only close my modal with "Close" button, not "Save changes".
This is my external modal template:
<div class="modal" id="modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document" ng-controller="modalController">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="task_id"> Task #{{clickedStop}}</h4>
</div>
<div class="modal-body">
<textarea id="description" class="form-control" placeholder="Description of work on a task"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="$hide()">Close</button>
<button type="button" class="btn btn-primary" ng-click="saveModal()">Save changes</button>
</div>
</div>
</div>
and my modalController:
app.controller('modalController', function($scope, $rootScope){
$scope.saveModal = function (){
$scope.ticket_id = $rootScope.clickedStop;
var tickets = localStorage.getItem($scope.ticket_id);
var task = JSON.parse(tickets);
$scope.description = jQuery("#description").val();
if($scope.description == "" || $scope.description == undefined)
{
alert("You must enter description!");
return;
};
var save = JSON.stringify({
":task_id":$scope.ticket_id,
":creator":task.creator,
":date_created":task.start,
":owner":task.owner,
":title":task.title,
":description":$scope.description
});
jQuery.ajax({
url:"engine/saveActivity.php",
method: "POST",
data:{data:save},
dataType:'json'
})
.success(function (responce){
if (responce === true){
console.log("Activity saved!");
//I wont to close modal here
}
}).error(function(data){
console.log("Error Activity save!"+ data);
});
};
When I tried to use $hide(), I get an error that $hide is not a function.
$hide() does not work because you not have included the $modal service :
app.controller('modalController', function($scope, $rootScope, $modal) {
^^^^^^
Now ng-click="$hide()" will work as expected. As the docs points out :
Append a bs-modal attribute to any element to activate the directive.
The module also exposes a $modal service Available for programmatic use
(inside a directive/controller).
But you must include it in order to use it.

ng-click directive not passing desired parameter

I have the following piece of angular code: (it's a modal-popover menu which uses the following js library: http://scruffles.github.io/BootstrapModalPopover/).
<div ng-repeat="purchasedItem in purchased" class="row item_summary">
<!-- edited for brevity -->
<div id="{{purchasedItem.code}}-popover" data-product-id="{{purchasedItem.code}}" class="popover" style="display: none;">
<div class="arrow"></div>
<h3 class="popover-title" style="display: none;"></h3>
<div class="popover-content">
<div class='popover-menu-left'>
<button class="btn btn-sm btn-danger" ng-click='purchasedItems.removePurchasedItem(purchasedItem)'>Verwijderen</button><br>
</div>
<div class='popover-menu-right-template'>
<div class='number-content' style="display: none;">
<div ng-controller="numpadCtrl as numpad" class="numpad">
<!-- edited for brevity -->
<input type="button" class="btn btn-sm" value="enter" data-item-id='{{purchasedItem.code}}' ng-click="numpad.flushNumber(purchasedItem.code)"></input>
</div>
</div>
</div>
<div class='popover-menu-right-content'>
</div>
</div>
</div>
</div>
the problem lies with this particular piece of code:
<input type="button" class="btn btn-sm" value="enter" data-item-id='{{purchasedItem.code}}' ng-click="numpad.flushNumber(purchasedItem.code)"></input>
The data-item-id attribute was added just to see if I could get retrieve the code - this works just fine! But when I set a breakpoint in the flushNumber function, the parameter passed is undefined.
The code for the numpad controller is the following (it doesn't really do anything yet)
sportOaseControllers.controller('numpadCtrl', ['$scope',
function($scope) {
var parent = this;
parent.currentEntry = "";
parent.addNumber = function (number) {
parent.currentEntry = parent.currentEntry.concat(number);
console.log(parent.currentEntry);
};
parent.cancel = function() {
console.log('cancelled!');
parent.currentEntry = "";
};
parent.flushNumber = function(code) {
console.log('flushing!' + code);
}
}]);
The only thing which might be a clue is that the $scope injected into the numpad controller is null - my knowledge of angular is too minimal to do any real debugging however. Can somebody point me in the right direction?
This is a working JSFiddle, what AngularJS version do you have?
controller as was introduce since 1.2 it's not available before that.
HMTL:
<div ng-app ng-controller="FirstCtrl">
{{purchasedItem}}
<div ng-controller="numpadCtrl as numpad" class="numpad">
<!-- edited for brevity -->
<input type="button" class="btn btn-sm" value="enter" data-item-id='{{purchasedItem.code}}' ng-click="numpad.flushNumber(purchasedItem.code)"></input>
</div>
</div>
JS:
function FirstCtrl($scope) {
$scope.purchasedItem = {
code: 'hello'
};
}
function numpadCtrl($scope) {
this.flushNumber = function (code) {
console.log(code);
}
}

Modal closes and new record appears to the screen despite of problems saving in a non-blocking call to the server

Problem Statement: How to prevent model to close and caller screen to update when there is a problem in async server call? For example, say I have a screen that list books on a screen like this. It also allows to perform CRUD operations. While creating and updating a new modal opens with a new controller.
Here is the HTML:
<li ng-repeat="book in books">
<div ng-click="updateBookModelOpen('lg', book, $index)">
<p class="text-center">{{book.name}}</p>
</div>
<div class="row text-center">
<a ng-click="remove(book)" class="undecorated-link">
<button class="btn btn-danger">Delete</button>
</a>
</div>
</li>
<button ng-click="createBookModelOpen('lg')" class="btn btn-primary">Add Your Book</button>
Here is logic for opening the modal, say this is inside BooksController:
this.createBookModelOpen = function(size) {
var modalInstance = $modal.open({
templateUrl: 'create-book.html',
controller: 'CreateBookModalController',
backdrop: 'static',
keyboard: false,
size: size,
scope: $scope
});
modalInstance.result.then(function(book) {
this.books.push(book);
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
Here is the logic for modal controller:
.controller('CreateBookModalController', ['$scope', '$modalInstance',
function($scope, $modalInstance) {
$scope.ok = function(book) {
$modalInstance.close(book);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
}
])
Here is the modal HTML:
<section data-ng-controller="CreateBooksController as createBooksCtrl" ng-init="createBooksCtrl.init()">
<div class="modal-header">
<h3 class="modal-title">Enter Book Details</h3>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<form class="form-horizontal" name="createBookForm" novalidate>
<fieldset>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" data-ng-model="book.name" id="name" class="form-control" placeholder="Book Name" required>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<div class="modal-footer">
<div class="row">
<div class="col-md-12">
<div class="pull-right">
<button class="btn btn-primary" ng-click="cancel()">Don't Save & Close</button>
<button class="btn btn-primary" ng-click="createBooksCtrl.create(book); ok(book)">Save & Close</button>
</div>
</div>
</div>
</div>
</section>
Here is my CreateBooksClientController:
this.create = function(book) {
book.$save(function(response) {
}, function(errorResponse) {
this.errors.push(errorResponse.data.messages);
});
};
The current behavior is that when I try to save an a book with the name that is rejected by the server. I get an error from the server but since this call is nonblocking, execution to ok() proceeds because ok() is next in sequence here.
<button class="btn btn-primary" ng-click="createBooksCtrl.create(book); ok(book)">Save & Close</button>
The book does not get saved in the database. But my modal closes and the new book is displayed to the screen because of this:
modalInstance.result.then(function(book) {
this.books.push(book);
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
Ideally it should not have been displayed in the list here as it has not yet been saved to the database.
<li ng-repeat="book in books">
<div ng-click="updateBookModelOpen('lg', book, $index)">
<p class="text-center">{{book.name}}</p>
</div>
</li>
Expected Result: Modal should not close, ok() call should not proceed when there is an error from the service. List should not display the new book if it is not saved to the database. How do you guys handle such scenario? Any help would be highly appreciated.
If you don't need to specifically use CreateBooksClientController, you could call book.$save in the modal controller as follows:
.controller('CreateBookModalController', ['$scope', '$modalInstance', '$http'
function($scope, $modalInstance, $http) {
$scope.ok = function(book) {
book.$save(function(response) {
$modalInstance.close(book);
}, function(errorResponse) {
// Error handling
})
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
}
])
The error handling will probably have to be changed accordingly. Then the ok button will be just:
<button class="btn btn-primary" ng-click="ok(book)">Save & Close</button>

Resources