Pass params between ng-click and a service Angular js - angularjs

I have a "search" where the user input a value and i want to send this value in the service because i want that another controller can have access. But for the moment i can't do it, if someone can help me it would be very usfull i using Angular js.
And the js
var app = angular.module('MainApp', [])
app.factory('Search', function($rootScope, $http){
var search = '';
function setSearch(bus){
search = bus;
}
function getSearch(){
return search;
}
return{
setSearch : setSearch,
getSearch: getSearch
};
//return myFactory;
/*
$scope.Search = function() {
return {
getDoctor: function () {
return $http.get('api/doctor' + $scope.search.searchText).then(function (response) {
orders = response.data;
$rootScope.$broadcast('handleSharedOrders', orders);
return orders;
})
}
};
}*/
});
app.controller('mainController', function ($scope, $http, Search) {
$scope.loadList = function() {
location.href = "doctors";
};
$scope.search.searchText = Search.getSearch();
$scope.Search = function(bus) {
console.log(bus);
Search.setSearch(bus);
}
$scope.doctors = {};
$http.get('/api/doctor').success(function (data) {
$scope.doctors = data;
})
.error(function (data) {
console.log('Error: ' + data);
});
/*
$http.get('/api/doctor/' + specialty).success(function (data) {
$scope.doctorsSpecialty = data;
})
.error(function (data) {
console.log('Error: ' + data);
});
*/
});
<!DOCTYPE html>
<html ng-app="MainApp">
<head lang="en">
<meta charset="UTF-8">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<!-- Cargamos app -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<script src="../Controllers/core.js"></script>
<title></title>
</head>
<body ng-controller="mainController">
<div align="center">
<img src="../img/logo.jpg" >
</div>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default" >
<div class="panel-heading" >
<h3 class="panel-title">Search Doctors</h3>
</div>
<div class="panel-body" >
<form role="form" >
<fieldset>
<div class="form-group" name="myForm" >
<input ng-model="search.searchText" type="text" class="form-control" placeholder="Search..." align="center">
</div>
<button class="btn btn-default" type="button" align="center" ng-click="Search(searchText)">
<b align="center">Search</b>
</button>
<!-- Change this to a button or input when using this as a form -->
</fieldset>
</form>
</div>
</div>
<div class="panel-heading" STYLE="background-color: #a7b5ce">
<h3 class="panel-title">List of Doctors</h3>
</div>
<div class="panel-body" >
<form role="form">
<fieldset>
<div class="form-group" name="myForm" >
<button class="btn btn-default" type="button" align="center" href=doctors ng-click="loadList()">
<b>List of Doctors</b>
</button>
</div>
<!-- Change this to a button or input when using this as a form -->
</fieldset>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
thank you for helping me

Here you have defined search.searchText:
<input ng-model="search.searchText" type="text" class="form-control" placeholder="Search..." align="center">
And here you are trying to pass just searchText (which is undefined):
<button class="btn btn-default" type="button" align="center" ng-click="Search(searchText)">
<b align="center">Search</b>
</button>
You need to either change your ng-model on your <input> to be 'search' or change the ng-click on your <button> to 'Search(search.searchText)'. If you choose to do the latter you may also want to explicitly create the search object in your controller.

I think you were doing it well, but your code has a few errors. First, you are not declaring the object search in your scope but you are assigning the property searchText to it. So you should do something like that:
$scope.search = {
searchText: ''
};
Then, in the view when you click search you are passing searchText but it should be search.searchText.
Have a look at this: https://jsfiddle.net/jruizx/54xcmgqp/

Related

Dynamic textbox validation using ng-repeat

I have following code which add dynamically textbox. The form contains Name and Programing skill textbox. The Programing skill textbox can be added dynamically.
I am trying to validate dynamic textbox. As of now it generates textbox every time when I click on "ADD" Button. If I entered anything in textbox then only it should be allowed to generate next textbox , else it should show a message/alert to fill the textbox.
I use ng-repeat to generate textbox.
<!DOCTYPE html>
<html>
<head>
<title>validation</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
</head>
<body>
<div ng-app="dynamicApp" ng-controller="dynamicController" class="container" style="width:600px;" ng-init="fetchData()">
<div class="alert alert-success alert-dismissible" ng-show="success" >
×
{{successMessage}}
</div>
<div class="alert alert-danger alert-dismissible" ng-show="error" >
×
{{errorMessage}}
</div>
<form method="post" ng-submit="submitForm()">
<div class="form-group">
<label>Enter Your Name</label>
<input type="text" name="name" id="name" ng-model="formData.person_name" class="form-control" />
</div>
<fieldset ng-repeat="row in rows">
<div class="form-group">
<label>Enter Your Programming Skill</label>
<div class="row">
<div class="col-md-9">
<input type="text" name="programming_languages[]" class="form-control" ng-model="formData.skill[$index + 1]" />
</div>
<div class="col-md-3">
<button type="button" name="remove" ng-model="row.remove" class="btn btn-danger btn-sm" ng-click="removeRow()"><span class="glyphicon glyphicon-minus"></span></button>
</div>
</div>
</div>
</fieldset>
<div class="form-group">
<button type="button" name="add_more" class="btn btn-success" ng-click="addRow()"><span class="glyphicon glyphicon-plus"></span> Add</button>
<input type="submit" name="submit" class="btn btn-info" value="Save" />
</div>
</form>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<tr>
<th>Name</th>
<th>Programming Languages</th>
</tr>
<tr ng-repeat="name in namesData">
<td>{{name.name}}</td>
<td>{{name.programming_languages}}</td>
</tr>
</table>
</div>
</div>
</body>
</html>
<script>
var app = angular.module('dynamicApp', []);
app.controller('dynamicController', function($scope, $http){
$scope.success = false;
$scope.error = false;
$scope.fetchData = function(){
$http.get('/home/testdata').success(function(data){
$scope.namesData = data;
});
};
$scope.rows = [{name: 'programming_languages[]', name: 'remove'}];
$scope.addRow = function(){
var id = $scope.rows.length + 1;
$scope.rows.push({'id':'dynamic'+id});
};
$scope.removeRow = function(row){
var index = $scope.rows.indexOf(row);
$scope.rows.splice(index, 1);
};
$scope.formData = {};
$scope.submitForm = function(){
$http({
method:"POST",
url:"/home/test",
data:$scope.formData
}).success(function(data){
if(data.error != '')
{
$scope.success = false;
$scope.error = true;
$scope.errorMessage = data.error;
}
else
{
$scope.success = true;
$scope.error = false;
$scope.successMessage = data.message;
$scope.formData = {};
$scope.rows = [{name: 'programming_languages[]', name: 'remove'}];
$scope.fetchData();
}
});
};
});
</script>

How to delay my ng-init function until my api call is success

I am working on dynamic form with ng-repeat. I am using oi-select for loading my location. I am loading this form inside modal popup. Regarding get my location values i am calling one api function on click of my modal open button. On success of this api call i was calling ng-init method. As per my requirement i should make this api call on click of modal open button. If i am clicking that button at first time, by default my first location value is not loaded inside select-box. Because my ng-init function called before my api call. Other than first time its working fine. Only first time it was not loaded that location[0] value defaultly . My question is how to delay this ng-init function?. Is there any other way to resolve this issue. Here i attached my plunker link .Please help me out from this issue. https://plnkr.co/edit/xDVetaZIzpFdKLS9ihU6?p=preview
html code
<body class="container row">
<div ng-app="myApp">
<div ng-controller="myCtrl">
<a class="btn btn-primary" data-toggle="modal" href='#modal-id' ng-click="getLocation()">Trigger modal</a>
<div class="modal fade" id="modal-id">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="user in users">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Location</label>
<oi-select ng-model="user.location" multiple oi-options="v for v in locations" ng-init='initLocation(user, locations)' name="select2" required>
</oi-select>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</div>
</div>
js code
var app = angular.module('myApp', ['ngResource', 'oi.select']);
app.factory('commonService', function($http, $q) {
return {
preFCSManualReleases: function() {
var deferred = $q.defer();
var url = "data.json";
$http.get(url, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: ''
}).then(function(data) {
deferred.resolve(data.data);
});
return deferred.promise;
}
}
});
app.controller('myCtrl', function($scope, commonService) {
$scope.getLocation = function() {
$scope.ids = [1, 2];
commonService.preFCSManualReleases().then(function(data) {
$scope.locations = data;
console.log('$scope.location[0]==============>', $scope.locations[0])
$scope.initLocation = (user, locations) => {
if (!user.location.length) {
user.location.push(locations[0]);
}
}
});
$scope.users = $scope.ids.map(function(id) {
return {
id: id,
comment: "",
location: []
};
});
}
$scope.adduser = function() {
var data = $scope.users.map(function(user) {
return {
"userid": user.id,
"manualcomment": user.comment,
"location": user.location
}
});
console.log("data", data)
}
});
You can put a condition on the oi-select parent:
<div class="col-md-3" ng-if="locationsLoaded">
<label>Location</label>
<oi-select ng-model="user.location" multiple oi-options="v for v in locations" ng-init='initLocation(user, locations)' name="select2" required>
</oi-select>
</div>
You can then control the $scope.locationsLoaded in your controller:
$scope.getLocation = function() {
$scope.locationsLoaded = false;
commonService.preFCSManualReleases().then(function(data) {
$scope.locations = data;
console.log('$scope.location[0]==============>', $scope.locations[0])
$scope.initLocation = (user, locations) => {
if (!user.location.length) {
user.location.push(locations[0]);
}
}
$scope.locationsLoaded = true; // we now have the required data
});
}
The ng-if will compile the element once locationsLoaded is true and when the ng-init is triggered, you are sure that there is data.

AngularJs Form validation ui-bootstrap modal

I'm trying to use a form with validation into a ui-bootstrap modal and the modal as a cancel button that just dismisses the view when clicked. The cancel is not working if there is validation errors. if I click again on the button then the modal closes. What am I possibly doing wrong?
http://plnkr.co/edit/loFUvJRfuycxd3qQwMgM?p=preview
angular.module('myApp', ['ui.bootstrap']);
angular.module('myApp').controller('TestCTRL', function ($scope,modalService) {
$scope.login = function () {
var modalOptions = {
closeButtonText: 'Cancel',
submitForm : function(form) {
if(form.$valid) {
console.log('Loggin in');
}
}
};
modalService.showModal({}, modalOptions).then(function (result) {
console.log('completed');
});
};
});
angular.module('myApp').service('modalService', function ($modal) {
var modalDefaults = {
backdrop: true,
keyboard: true,
modalFade: true,
templateUrl: 'login.html'
};
var modalOptions = {
closeButtonText: 'Close',
actionButtonText: 'OK',
headerText: 'Proceed?',
bodyText: 'Perform this action?'
};
this.showModal = function (customModalDefaults, customModalOptions) {
if (!customModalDefaults) customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return this.show(customModalDefaults, customModalOptions);
};
this.show = function (customModalDefaults, customModalOptions) {
//Create temp objects to work with since we're in a singleton service
var tempModalDefaults = {};
var tempModalOptions = {};
//Map angular-ui modal custom defaults to modal defaults defined in service
angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);
//Map modal.html $scope custom properties to defaults defined in service
angular.extend(tempModalOptions, modalOptions, customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function ($scope, $modalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.ok = function (result) {
$modalInstance.close(result);
};
$scope.modalOptions.close = function (result) {
$modalInstance.dismiss('cancel');
};
}
}
return $modal.open(tempModalDefaults).result;
};
});
<!DOCTYPE html>
<html>
<head >
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="ui-bootstrap.js"></script>
<meta charset="utf-8">
<title>test</title>
</head>
<body ng-app="myApp">
<div ng-controller="TestCTRL">
<button type="button" ng-click="login()">Login</button>
</div>
<script src="app.js"></script>
</body>
</html>
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4">
<div class="account-wall">
<h1 class="text-center login-title">Login</h1>
<form name="loginForm" ng-submit="modalOptions.submitForm(loginForm)" class="form-signin" novalidate>
<div class="form-group">
<label for="email" class="control-label">Email</label>
<input id="email" type="email" name="email" placeholder="Email"
class="form-control" ng-model="user.email" required autofocus>
<div ng-messages="loginForm.email.$error" ng-if="loginForm.$submitted || loginForm.email.$touched" class="errors">
<div ng-message="required">Value required</div>
<div ng-message="email">Valid email required</div>
</div>
</div>
<div class="form-group">
<label for="password" class="control-label">Password</label>
<input id="password" type="password" name="password" placeholder="Password"
class="form-control" ng-model="user.password" required>
<div ng-messages="loginForm.password.$error" ng-if="loginForm.$submitted || loginForm.email.$touched" class="errors">
<div ng-message="required">password is required</div>
</div>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">
Login
</button>
<button class="btn btn-lg btn-primary btn-block" type="button" ng-click="modalOptions.close()">
{{modalOptions.closeButtonText}}
</button>
</form>
</div>
</div>
</div>
</div>
Thanks so much for your help.
I resolved it by setting the form to pristine before closing the modal, in the cancel action function
function _cancel()
{
$scope.newForm.$setPristine();
$modalInstance.close();
}

How to push html element

first, iam using AngularJS v1.3.14
i try to push : label ,input ,button html element
here my html code:
<div class="container" ng-controller="ctrl" >
<div class="form-inline" ng-repeat="c in controls">
<label class="control-label">Name:</label>
<input class="form-control">
<button class="btn btn-danger">X</button>
</div>
<button class="btn btn-primary" ng-click="add();">+</button>
and script code:
angular.module("app", [])
.controller("ctrl", function ($scope) {
$scope.controls=[];
$scope.add = function () {
$scope.controls.push({
...
})
};
});
and my question is: how can i push div with controls id.
try this, you need to dynamically add the html controls in a array then re-rendering the array abject values by using ng-repeat
Html code
<div class="form-inline" ng-repeat="c in controls">
<div ng-bind-html="c.htmlValue | to_trusted"></div>
</div>
<button class="btn btn-primary" ng-click="add();">+</button>
Js Code
angular.module("app", [])
.controller("ctrl", function ($scope) {
$scope.controls=[];
$scope.add = function () {
var stringValue="<label class=\'control-label\'>Name:</label><input class=\'form-control\'><button class=\'btn btn-danger\'>X</button>"
$scope.controls.push({ "htmlValue": stringValue })
};
}).filter('to_trusted', ['$sce', function ($sce) {
return function(text) {
return $sce.trustAsHtml(text);
};
}]);
See this working code in
Plunker
Demo Image
finally i found the solution:
html:
<div class="container" ng-controller="ctrl">
<div class="form-inline" ng-repeat="todo in todos track by $index">
<label class="control-label">Name:</label>
<input type="text" class="form-control" ng-model="todos[$index]">
<button class="btn btn-danger" ng-click="remove($index);">X</button>
</div>
<div class="form-inline">
<button class="btn btn-primary" ng-click="add();">+</button>
</div>
scripts:
angular.module('app', [])
.controller('ctrl', function ($scope) {
$scope.todos = [''];
$scope.add = function () {
$scope.todos.push({});
console.log($scope.todos);
};
$scope.remove = function (index) {
$scope.todos.splice(index, 1);
};
});
hope this help.
The button was not inside the scope of the controller. At the bottom you can find a link with the PLNKR demonstratic a basic use.
angular.module("app", [])
.controller("ctrl", function ($scope) {
$scope.controls=[];
$scope.add = function () {
$scope.controls.push('')
};
});
HTML:
<body ng-app="app">
<div ng-controller="ctrl" >
<div class="container" >
<div class="form-inline" ng-repeat="c in controls">
<label class="control-label">Name:</label>
<input class="form-control" ng-model="c">
<button class="btn btn-danger">X</button>
</div>
</div>
<button class="btn btn-primary" ng-click="add();">+</button>
</div>
</body>
Example

Add & delete note in AngularJS

I am new at AngularJS and I am trying to figure out how to add and delete notes to the setup that I have created. I have tried a lot of different things but I cant figure out how to get it to work.
I have cleaned up my code so it should be easier to figure out.
Please take a look at the jsfiddle version or snippet of my code:
'use strict'
var app = angular.module('plunker', ['ui.sortable']);
app.controller('MainCtrl', function($scope) {
var i;
$scope.itemsList = {
items1: [],
items2: []
};
for (i = 0; i <= 5; i += 1) {
$scope.itemsList.items1.push({
'Id': i,
'Label': 'Item ' + i
});
}
$scope.sortableOptions = {
containment: '#sortable-container',
accept: function(sourceItemHandleScope, destSortableScope) {
return sourceItemHandleScope.itemScope.sortableScope.$id === destSortableScope.$id;
}
};
});
.as-sortable-item,
.as-sortable-placeholder {} #sortable-container {} .touch-mover {
float: right;
padding: 3px;
margin-top: 5px;
}
<html ng-app="plunker">
<head>
<script data-require="angular.js#1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.17"></script>
<script src="https://rawgithub.com/a5hik/ng-sortable/master/dist/ng-sortable.js"></script>
</head>
<body ng-controller="MainCtrl">
<div id="sortable-container">
<div class="form-actions">
<div class="input-append">
<form>
<input class="span3" size="16" type="text" placeholder="Add a note">
<button class="btn btn-success" type="button" ng-disabled="" ng-click="">
Add Note
</button>
</form>
</div>
</div>
<div class="sortable-row" as-sortable="sortableOptions" ng-model="itemsList.items1">
<div ng-repeat="item in itemsList.items1" class="simpel-fighter-input" as-sortable-item>
<input class="category-form textboxid" type="text" name="input" ng-model="item.Label" placeholder="Deltager1">
<div as-sortable-item-handle class="touch-mover">MOVE ME</div>
<a ng-click="" href>
<div class="touch-mover">DELETE</div>
</a>
<input class="category-form textboxid" style="float:right" type="text" name="input" ng-model="item.Label2" placeholder="Deltager2">
</div>
</div>
</div>
</body>
</html>
For adding a note just insert into your controller MainCtrl this function:
$scope.addNote = function() {
$scope.itemsList.items1.push({"Id" : $scope.itemsList.items1.length, "Label": "Item " + $scope.itemsList.items1.length})
}
and edit your form (add ng-model to input and ng-click function to button) like:
<input class="span3" size="16" type="text" ng-model="noteText" placeholder="Add a note">
<button class="btn btn-success" type="button" ng-disabled="" ng-click="addNote()">
Add Note
</button>
For deleting use in you controller something like
$scope.deleteNote = function(index) {
$scope.itemsList.items1.splice(index,1)
}
and attach this function to the tag "DELETE" like
ng-click="deleteNote($index)"
I hope this helps.

Resources