I have a AngularJS SPA what contains a text input on a modal, on Page load the modals inputs are set to their desired initial state through a scope function which is called.
Modal
<input class="form-control" ng-model="PatientName" name="PatientName" id="PatientName" />
<button type="button" class="btn btn-default" ng-click="setvals()" data-dismiss="modal">Close</button>
App.js
var app = angular.module("TrollyPatientApp", ['TrollyPatientFilters']);
app.controller("NewPartientModalController", function ($scope, $filter) {
console.log("controller Loaded...")
$scope.setvals = function () {
console.log($scope);
console.log("Setting Intial New Patient Values.")
$scope.PatientName = "john";
$scope.setDateAsNowCB = true; //True = Readonly, false = enabled.
$scope.ArrivalDateInEd = $filter('date')(new Date(), 'dd/MM/yyyy');//Injecting the date (through the filter) into the ArrivalDateInED field.
console.log($scope);
}
$scope.setvals();
});
When the close button is clicked on the modal i want it to reset all the values back to default.
At present it does this by calling setvals(). I can see it being called from the debug console however it doesn't seem to effect the input value....
On load you should create a object patient that would have all the information about the patient, store it inside some variable on init. & on reset rebind that copy to the actual patient model.
Controller
app.controller("NewPartientModalController", function ($scope, $filter) {
console.log("controller Loaded...")
$scope.patient = {};
$scope.setvals = function () {
console.log($scope);
console.log("Setting Intial New Patient Values.")
$scope.patient.PatientName = "john";
$scope.patient.setDateAsNowCB = true; //True = Readonly, false = enabled.
$scope.patient.ArrivalDateInEd = $filter('date')(new Date(), 'dd/MM/yyyy');//Injecting the date (through the filter) into the ArrivalDateInED field.
//save copy of initial object in some variable
$scope.copyOfInitialPatient = angular.copy($scope.patient);
}
$scope.reset = function(){
//assign initial copy again to patient object.
$scope.patient = angular.copy($scope.copyOfInitialPatient);
}
$scope.setvals();
});
You need to define $scope.PatientName = "john"; outside of $scope.setvals for first, then changing value in setvals() will work.
var app = angular.module("TrollyPatientApp", []);
app.controller("NewPartientModalController", function ($scope, $filter) {
console.log("controller Loaded...")
$scope.PatientName = "john";
$scope.setvals = function () {
console.log($scope);
console.log("Setting Intial New Patient Values.")
$scope.PatientName = "john";
$scope.setDateAsNowCB = true; //True = Readonly, false = enabled.
$scope.ArrivalDateInEd = $filter('date')(new Date(), 'dd/MM/yyyy');//Injecting the date (through the filter) into the ArrivalDateInED field.
console.log($scope);
}
$scope.setvals();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="TrollyPatientApp" ng-controller="NewPartientModalController">
<input class="form-control" ng-model="PatientName" name="PatientName" id="PatientName" />
<button type="button" class="btn btn-default" ng-click="setvals()" data-dismiss="modal">Close</button>
</body>
Related
im having ng-change function in the name of myFunc() to store the response from html listitem.
the respose value is getting saved in the local variable of the function but when i refresh the controller or page the values are deleted. i need to store the value during ng-change in myFunc() after multiple page or controller refersh the value will be stored in the controller variable to do the further logics
on page onload
myhtml code
<div class="col-sm-4">
<ol name="ManualFiles" title="Select" required validType="select" ng-
change="myFunc()" ng-model="data.manualsFiles" ng-selected="
{{data.manualsFiles}}">
<li nya-bs-option="type in manualsFiles" data-value="type.key">
<a> {{type.val}} </a>
</li>
</ol>
</div>
mycontroller code
$scope.myFunc = function() {
var manualFile=$scope.data.manualsFiles;
var cdSoftwares=$scope.data.cdSoftware;
var price=$scope.data.priceBook;
var referenceBooks=$scope.data.referenceBook;
var vpnAccounts=$scope.data.vpnAccount;
if((manualFile && cdSoftwares && price && referenceBooks && vpnAccounts)!==0)
{
$scope.isTypeDisabled=false;
}
else
{
$scope.isTypeDisabled=true;
$scope.data.status="Pending";
}
};
Try it using sessionStorage. In that way, you would not lose your values at least the user closes the window.
Now, the idea is, in the function myFunc,
$scope.myFunc = function() {
var manualFile=$scope.data.manualsFiles;
var cdSoftwares=$scope.data.cdSoftware;
var price=$scope.data.priceBook;
var referenceBooks=$scope.data.referenceBook;
var vpnAccounts=$scope.data.vpnAccount;
//Here, use sessionStorage to save your values in the browser.
var data = {'manualFile': manualFile, 'cdSoftwares': cdSoftwares, 'price': price, 'referenceBooks': referenceBooks, 'vpnAccounts': vpnAccounts}
sessionStorage.setItem('yourNameKey', data);
if((manualFile && cdSoftwares && price && referenceBooks && vpnAccounts)!==0)
{
$scope.isTypeDisabled=false;
}
else
{
$scope.isTypeDisabled=true;
$scope.data.status="Pending";
}
};
Then, when Users are refreshing the site, you would create a function just for recover that values in your variables. You'd use destructuring assignment to recover your values.
function recoverValues() {
var data = sessionStorage.getItem('yourNameKey');
var { manualFile, cdSoftwares, price, referenceBooks, vpnAccounts } = data;
}
recoverValues();
You can use sessionStorage property of $window.
Note: The data stored using sessionStorage will be available only in that session. (data will get deleted when the browser tab is closed)
You can achieve your requirement using this example. Try this demo
<script type="text/javascript">
var app = angular.module('MyApp', ["ngStorage"])
app.controller('MyController', function ($scope, $localStorage, $sessionStorage, $window) {
$scope.Save = function () {
$localStorage.LocalMessage = "LocalStorage: My name is Pet Jones.";
$sessionStorage.SessionMessage = "SessionStorage: My name isPet Jones.";
OR
$sessionStorage.setItem("status", "pending");
}
$scope.Get = function () {
$window.alert($localStorage.LocalMessage + "\n" + $sessionStorage.SessionMessage);
OR
console.log($sessionStorage.getItem("status"))
}
});
</script>
I have a page employee.html with a list of dependents and for each row (li) an inner button with the directive ng-click="editDependent({{dependent.id}})". That button tries to call a modal box.
The employee.html is loaded in a ui_view div from an index.html
I saw that each button in view source with chrome are correctly bound ng-click="editDepedent(1)" and so on.
But at the same time I have an error
angular.min.js:118 Error: [$parse:syntax] http://errors.angularjs.org/1.5.8/$parse/syntax?p0=%7B&p1=invalid%20key&p2=11&p3=editDependent(%7B%7Bdependent.id%7D%7D)&p4=%7Bdependent.id%7D%7D)
I'm trying to pass my dependent id to my modal and the previous scope also that contains the info about the employee. So how can I achieve this parameter passing?
This is my main controller
app.controller('EmployeeController', function ($scope, $stateParams, $uibModal, EmployeeService) {
if($stateParams.id){
EmployeeService.getEmployee($stateParams.id).then(function(employee){
$scope.employee = employee;
EmployeeService.setCurrentEmployee(employee);
});
}
$scope.editDependent = function(id){
if(id){
$scope.dependentid = id;
}
var uibModalInstance = $uibModal.open({
templateUrl : 'modal_dependent.html',
controller : 'DependentController',
scope: $scope
});
return uibModalInstance;
}
});
This is my dependent controller to catch the value
app.controller('DependentController', function($scope, $uibModal, $uibModalInstance, $stateParams, EmployeeService){
//Following line does not work because it gets the ID of employee which is passed by querystring
//var dependentID = $stateParams.id;
if($scope.dependentid){
var currentEmployee = EmployeeService.getCurrentEmployee();
//find the current dependent
for(var i = 0; i < currentEmployee.dependents.length; i++){
//*****************************************************
//Hardcoding 1 to test the dependent number 1 but it should be the dependent id parameter
if(currentEmployee.dependents[i].id == 1){
$scope.dependent = currentEmployee.dependents[i];
break;
}
}
}else{
$scope.dependent = { id : 0 };
}
$scope.editableDependent = angular.copy($scope.dependent);
//Submit button in modal
$scope.submitDependent = function(){
DependentService.saveDependent($scope.editableDependent);
$scope.dependent = angular.copy($scope.editableDependent);
$uibModalInstance.close();
}
});
UPDATE
employee.html
<form name="employee_form">
<div>
<h1> {{employee.name}} </h1>
<h3>Dependents</h3>
<button class="btn bgcolor-rb-main" x-ng-click="editDependent(0)">
Add new
</button>
<ul class="list-inline">
<li x-ng-repeat="dependent in employee.dependents">
<button x-ng-click="editDependent({{dependent.id}})">
Edit
</button><br>
<div>{{dependent.name}}</div>
</li>
</ul>
</div>
</form>
This is my modal_dependent.html
<div class="modal-header">
<h4>Dependent</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" id="txtName" x-ng-model="editableDependent.name" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" x-ng-click="discardChanges()">Discard</button>
<button type="submit" class="btn btn-primary" x-ng-click="submitDependent()">Save</button>
</div>
UPDATE
I changed my controller to initialize before $scope.dependent
app.controller('DependentController', function($scope, $uibModal, $uibModalInstance, $stateParams, EmployeeService){
//Following line does not work because it gets the ID of employee which is passed by querystring
//var dependentID = $stateParams.id;
$scope.dependent = { id : 0 };
if($scope.dependentid){
var currentEmployee = EmployeeService.getCurrentEmployee();
//find the current dependent
for(var i = 0; i < currentEmployee.dependents.length; i++){
//*****************************************************
//Hardcoding 1 to test the dependent number 1 but it should be the dependent id parameter
if(currentEmployee.dependents[i].id == 1){
$scope.dependent = currentEmployee.dependents[i];
break;
}
}
}
$scope.editableDependent = angular.copy($scope.dependent);
//Submit button in modal
$scope.submitDependent = function(){
DependentService.saveDependent($scope.editableDependent);
$scope.dependent = angular.copy($scope.editableDependent);
$uibModalInstance.close();
}
});
SOLVED
My button changed from this
<button x-ng-click="editDependent({{dependent.id}})">Edit</button>
To this
<button x-ng-click="editDependent(dependent.id)">Edit</button>
i think there is parsing error you have to define
$scope.dependentid = {};
before using it,
or otherwise you can use it as a model (if you are submitting a form on frontend like this)
<input type="hidden" ng-model="dependentid" />
it will be better to understand for me if you edit the code and add some frontend html
I need to reflect some changes to controller B (inside some event) when I make change at controller A. For that I am using a service.
When I am changing service value from FirstCtrl, ng-change is not firing at SecondCtrl. Is there anything I have missed or need to change?
Please note that I am using angular 1.5.6. and don't want to use watch or even scope.
Below is my code.
var myApp = angular.module('myApp', []);
myApp.factory('Data', function() {
return {
FirstName: ''
};
});
myApp.controller('FirstCtrl', ['Data',
function(Data) {
var self = this;
debugger
self.changeM = function() {
debugger
Data.FirstName = self.FirstName;
};
}
]);
myApp.controller('SecondCtrl', ['Data',
function(Data) {
var self = this;
self.FirstName = Data;
self.changeM = function() {
alert(1);
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="FirstCtrl as c">
<input type="text" ng-model="c.FirstName" data-ng-change="c.changeM()">
<br>Input is : <strong>{{c.FirstName}}</strong>
<div ng-controller="SecondCtrl as c1">
Input should also be here: {{c1.FirstName}}
<input type="text" ng-model="c1.FirstName" data-ng-change="c1.changeM()">
</div>
</div>
<hr>
</div>
As you dont want to use $scope trying modifying the code in order to use $emit and $on feature in angular js to communicate between two controllers. You can refer this link.
var myApp = angular.module('myApp', []);
myApp.factory('Data', function() {
return {
FirstName: ''
};
});
myApp.controller('FirstCtrl', ['Data',
function(Data) {
var self = this;
debugger
self.changeM = function() {
debugger
//Data.FirstName = self.FirstName;
Data.$on('emitData',function(event,args){
Data.FirstName=args.message
document.write(Data.FirstName)
})
};
}
]);
myApp.controller('SecondCtrl', ['Data',
function(Data) {
var self = this;
self.FirstName = Data;
self.changeM = function() {
Data.$emit('emitData',{
message:Data.FirstName
})
};
}
]);
The only way then is to directly copy the reference of the data object within the controller. Note that you don't need ng-change to update the value then.
If you want something else, either wrap the FirstName in a sub object of Data and do the same i did :
Data = {foo:'FirstName'};
Or use $watch since it's the whole purpose of that function.
Here is a working code with copying the Data object in the controller.
var myApp = angular.module('myApp', []);
myApp.factory('Data', function() {
return {
FirstName: ''
};
});
myApp.controller('FirstCtrl', ['Data',
function(Data) {
var self = this;
self.Data=Data;
debugger
self.changeM = function() {
debugger
};
}
]);
myApp.controller('SecondCtrl', ['Data',
function(Data) {
var self = this;
self.Data = Data;
self.changeM = function() {
alert(1);
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="FirstCtrl as c">
<input type="text" ng-model="c.Data.FirstName" data-ng-change="c.changeM()">
<br>Input is : <strong>{{c.Data.FirstName}}</strong>
<div ng-controller="SecondCtrl as c1">
Input should also be here: {{c1.Data.FirstName}}
<input type="text" ng-model="c1.Data.FirstName" data-ng-change="c1.changeM()">
</div>
</div>
<hr>
</div>
The only way I know to solve the problem is using watch, unfortunately. (I am new to angular.)
From the ngChange document (https://docs.angularjs.org/api/ng/directive/ngChange):
The ngChange expression is only evaluated when a change in the input value causes a new value to be committed to the model.
It will not be evaluated:
if the value returned from the $parsers transformation pipeline has not changed
if the input has continued to be invalid since the model will stay null
**if the model is changed programmatically and not by a change to the input value**
I have a form with two input fields (session.email and session.psw) bound to the LoginController.session attribute. When I click the reset button, I call the LoginController.reset() function.
I would like make it clear the session attribute, utilizing the variable sessionDefault (empty). However it works just one time, if I reset two times the form, sessionDefault is undefined.
How could I make it as a constant attribute of the controller?
app.controller('LoginController', function ($scope)
{
this.session={};
var sessionDefault=
{
email : "",
psw: ""
};
this.reset = function()
{ this.session = sessionDefault; };
});
Try out this out
for reset function just reset it with sessionDefault copy like as shown below
vm.reset = function () {
vm.session = angular.copy(sessionDefault);
};
here this refers to the controller instance
Notice that I use var vm = this; and then I decorate vm with the members that should be exposed and data-bindable to to the View. vm simply denotes view modal
This does 3 things for me.
Provides a consistent and readable method of creating bindings in my controllers
Removes any issues of dealing with this scoping or binding (i.e. closures in nested functions)
Removes $scope from the controller unless I explicitly need it for something else
Working Demo
script
var app = angular.module('myApp', []);
app.controller('LoginController', function ($scope) {
var vm = this;
vm.session = {};
var sessionDefault = {
email: "",
psw: ""
};
vm.reset = function () {
vm.session = angular.copy(sessionDefault);
};
});
html
<div ng-app='myApp' ng-controller="LoginController as login">
Email:<input type="text" ng-model="login.session.email"/>{{login.session.email}}
<br>
Psw:<input type="text" ng-model="login.session.psw"/>{{login.session.psw}}
<br>
<button ng-click="login.reset()">Reset</button>
</div>
Take a look at this beautiful stuff.
AngularJS’s Controller As and the vm Variable
this.reset = function()
{ this.session = sessionDefault; };
The this in this context refers to the function (reset). If you want to access the 'original' this you need to store it in a variable.
app.controller('LoginController', function ($scope)
{
this.session={};
var sessionDefault=
{
email : "",
psw: ""
};
var self = this;
this.reset = function()
{ self.session = angular.clone( sessionDefault); };
});
I have a scope variable, when it returns true, i need to trigger some events or do something. I my case, the every first time, the scope variable returns undefined and later it returns true. In this case i used $watch method to get the expected funcionality. Is there any alternative approach to do the same instead using $watch ?
scope.$watch () ->
scope.initiateChild
, (value) ->
if value is true
$timeout ->
scope.buildOnboarding()
, 1000
You can try using AngularJS $on(), $emit() and $broadcast().
Here is an example: http://www.binaryintellect.net/articles/5d8be0b6-e294-457e-82b0-ba7cc10cae0e.aspx
You can use JavaScript getters and setters without any expense of using $watch.
Write code in the setter to do what you want when angular changes the your model's value you are using in scope. It gets null or an a State object as user types. Useful for working with type ahead text boxes that have dependencies on each other. Like list of counties after typing state without user selecting anything.
Here is some pseudo style code to get the idea.
<input ng-model="searchStuff.stateSearchText" />
<div>{{searchStuff.stateObject.counties.length}}</div>
<div>{{searchStuff.stateObject.population}}</div>
$scope.searchStuff=new function(){var me=this;};
$scope.searchStuff.stateObject = null;
$scope.searchStuff.getStateObjectFromSearchText = function(search){
// get set object from search then
return stateObject;
};
$scope.searchStuff._stateSearchText= "";
Object.defineProperty($scope.searchStuff, 'stateSearchText', {
get: function () {
return me._stateSearchText;
},
set: function (value) {
me,_stateSearchText = value;
me.stateObject = getStateObjectFromSearchText (value);
}
});
See this fiddle: http://jsfiddle.net/simpulton/XqDxG/
Also watch the following video: Communicating Between Controllers
A sample example is given below
Html:
<div ng-controller="ControllerZero">
<input ng-model="message" >
<button ng-click="handleClick(message);">LOG</button>
</div>
<div ng-controller="ControllerOne">
<input ng-model="message" >
</div>
<div ng-controller="ControllerTwo">
<input ng-model="message" >
</div>
javascript:
var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function(msg) {
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
function ControllerZero($scope, sharedService) {
$scope.handleClick = function(msg) {
sharedService.prepForBroadcast(msg);
};
$scope.$on('handleBroadcast', function() {
$scope.message = sharedService.message;
});
}
function ControllerOne($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'ONE: ' + sharedService.message;
});
}
function ControllerTwo($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'TWO: ' + sharedService.message;
});
}
ControllerZero.$inject = ['$scope', 'mySharedService'];
ControllerOne.$inject = ['$scope', 'mySharedService'];
ControllerTwo.$inject = ['$scope', 'mySharedService'];