Using $rootscope to change ng-show between controllers - angularjs

What I want to do is pretty simple. I have two forms. One form is visible in the beginning and once that form is submitted it dissappears and the second form appears. I am trying to use a flag variable set at $rootscope.showFlag but it doesn't seem to work.
Here is my HTML part:
<div ng-app="myapp" >
<div class="container" ng-controller="addItemController" ng-show="showFlag">
<form class="form-signin">
<h2 class="form-signin-heading">Add an item</h2>
<input type="text" name="itemName" ng-model="myForm.itemName" id="inputItemName" class="form-control" placeholder="Name of the item" autofocus required>
<button class="btn btn-lg btn-primary btn-block" ng-click="myForm.submitTheForm()">Add item</button>
</form>
</div> <!-- /container -->
<div class="container" ng-controller="MyCtrl" ng-show="!showFlag">
<input type="text" ng-model="username"></br></br>
<button class="btn btn-lg btn-primary btn-block" ngf-select ng-model="files">Select file</button>
</div>
</div>
And this is my Angular app:
var app = angular.module("myapp", ['ngFileUpload'])
.run(function($rootScope) {
$rootScope.showFlag = true;
});
app.controller("addItemController", function($rootScope, $scope, $http) {
$scope.myForm = {};
$scope.showFlag = true;
Data.Show = 10;
$scope.myForm.submitTheForm = function(item, event)
{
console.log("--> Submitting form");
var dataObject = {
itemName : $scope.myForm.itemName,
};
var responsePromise = $http.post("/angularjs-post", dataObject, {});
responsePromise.success(function(dataFromServer, status, headers, config) {
console.log(dataFromServer.title);
//alert("Submitting form OK!");
$rootScope.showFlag = false;
});
responsePromise.error(function(data, status, headers, config) {
alert("Submitting form failed!");
});
}
$scope.myForm.uploadPhoto = function(item, event)
{
console.log('Uploading photo');
}
});
app.controller('MyCtrl', ['$scope', 'Upload', function ($rootScope, $scope, Upload) {
$scope.$watch('files', function () {
$scope.upload($scope.files);
});
$scope.log = '';
$scope.upload = function (files) {
if (files && files.length) {
var file = files[0];
Upload.upload({
url: '/upload',
fields: {
'username': $scope.username
},
file: file
}).progress(function (evt) {
// during progress
}).success(function (data, status, headers, config) {
// after finishing
});
}
};
}]);

You set showFlag to true in two places.
In the root scope.
.run(function($rootScope) {
$rootScope.showFlag = true;
});
And in the local scope.
app.controller("addItemController", function($rootScope, $scope, $http) {
$scope.myForm = {};
$scope.showFlag = true;
As the ng-show for the first form looks in the local scope first it won't be affected even when you set the rootScope flag to false.

One possible reason could be that you have misspelled the controller name
it should be addSellItemController.
<div class="container" ng-controller="addSellItemController" ng-show="showFlag">
Another small mistake is you have not added $rootScope as a dependency in your MyCtrl directive.
app.controller('MyCtrl', ['$rootScope','$scope', 'Upload', function ($rootScope, $scope, Upload) {
...
});

Related

How can i execute angular script after onclick event

Here is my html code:
<div ng-app="myApp" ng-controller="customersCtrl">
<p id="druzyny"></p>
</div>
and then in angular script:
var app = angular.module('myApp', []);
document.getElementById("search1").onclick = app.controller('customersCtrl', function($scope, $http){
var place = document.getElementById("place").value;
var sel1 = document.getElementById("sel1").value;
var sel2 = document.getElementById("sel2").value;
var req = {
method: 'post',
url: 'findTournament',
headers: {
'Content-type': 'application/json'
},
data: {place: 'test'}
};
$http(req).then(function(response){
});
});
I`ve got button id="search1" and i want that angular execute only when i click this button, no automatically when page is reload, is it possible?
Thanks for answears
HTML:
<div ng-app="myApp" ng-controller="customersCtrl as customers">
<input data-ng-model="customers.place">
<input data-ng-model="customers.sel1">
<input data-ng-model="customers.sel2">
<button data-ng-click="customers.init()"></button>
</div>
JS:
angular.module('myApp', []);
angular
.module('myApp')
.controller('customersCtrl', function($scope, customersService){
var vm = this;
vm.init = function(){
customersService.findTournament({place: vm.place, sel1: vm.sel1, sel2: vm.sel2})
.then(function(res){});
};
});
angular
.module('myApp')
.service('customersService', function($http){
return {
findTournament: findTournament
};
function findTournament(data){
return $http.post('findTournament', data);
}
});

Angular: Submit a post request from a modal and refresh the main page

So I have a main controller with some data (fetched by $http.get), and when you click on one item, it pops up a modal with more details.
In my modal, there is a button to modify the data (sent by $http.post) which then closes the modal and needs to tell the parent controller to refresh the data, because it has been modified by the event in the modal.
HTML
<!--MODAL WINDOW for item details -->
<script type="text/ng-template" id="itemModalContent.html">
<div class="modal-dialog ng-hide="hidden">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="cancel right button" data-dismiss="modal" aria-hidden="true" ng-click="cancel()"><i class="fa fa-close"></i></button>
<span class="item-name">{{item.name}}</span>
</div>
<div class="modal-body">
<p class="description">{{item.description}}</p>
<input type="hidden" ng-model="item.uniqueid" id="uniqueid" value="{{item.uniqueid}}" name="uniqueid"/>
<p class="response"> {{PostDataResponse}}</p>
<p class="error"> {{ResponseDetails}}</p>
</div>
<div class="modal-footer">
<button type="button" class="button cancel btn-default" data-dismiss="modal" ng-click="cancel()">Cancel</button>
<button type="button" class="button ok btn-primary" ng-click="confirm()">Submit</button>
</div>
</div>
</div>
</script>
Angular
/* main controller - items */
myApp.controller('itemsCtrl', function ($scope, $rootScope, $http, $uibModal) {
//wrap $http.get request in a function
$scope.loadMyData = function () {
url = '<your_server>';
$http.get(url).then(function (response) {
$scope.items = response.data;
$scope.showModal = false;
$scope.open = function (item) {
$('.overlay').show();
var modalInstance = $uibModal.open({
controller: "itemsModalInstanceCtrl",
templateUrl: 'itemModalContent.html',
resolve: {
item: function () {
return item;
}
}
});
};
});
}
//initial load
$scope.loadMyData();
//event listener for refresh_items event
$rootScope.$on('refresh_items', function (event, data) {
console.log(data);
$scope.loadMyData();
});
});
/* modal instance - item */
myApp.controller('itemsModalInstanceCtrl', function ($http, $scope, $timeout, $uibModalInstance, item) {
$scope.item = item;
$scope.cancel = function () {
$uibModalInstance.dismiss();
$('.overlay').hide();
};
updateUrl = '<your_webservice_url>';
$scope.confirm = function () {
var myitemid = $scope.item.uniqueid;
// use $.param jQuery function to serialize data from JSON
var data = $.param({
uniqueid: myitemid
});
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post(updateUrl, data, config)
.success(function (data, status, headers, config) {
$scope.PostDataResponse = "You have successfully submitted your data";
})
.error(function (data, status, header, config) {
$('.response').addClass('error');
$scope.ResponseDetails = "data: " + data +
"<br />status: " + status +
"<br />headers: " + header +
"<br />config: " + config;
});
$timeout(function () {
$uibModalInstance.close({});
$('.overlay').hide();
//tell parent controller to refresh the data
$scope.$emit('refresh_items', data);
}, 3000);
}
});

Angularjs checkbox initialization issue using json object

So i have a checkbox page barely working, the issue is when i first start this page, the checkbox is not checked, even though i try to initialize it from backend node server. No error in browser debugger though.
in the server mye,
app.get('/2getMyDiagValue', function(req, res)
{
console.log("get my diag");
var formDataArray = { "formDataObjects": [
{"flagName":"myStuff1", "flagVal":0},
{"flagName":"myStuff2", "flagVal":1}
]};
res.contentType('application/json');
res.send(formDataArray);
});
app.post('/2setMyDiagValue', function(req, res)
{
......
}
in the client mye,
app.controller('myDiagController', function($scope, $http, $routeParams, QueryMyService) {
$scope.message = 'SID Diagnostics';
// using http.get() to get existing my setting from server mye
QueryMyService.getInfoFromUrl7('/2getMyDiagValue').then(function(result) {
$scope.formData = result.formDataObjects;
}, function(error) {
alert("Error");
} );
$scope.submitForm = function() {
console.log("posting form data ...");
$http.post("/2setMyDiagValue",
JSON.stringify($scope.formData)).success(function(){} );
};
});
app.factory('QueryMyService', function($http, $q, $location) {
var factory = {};
var browserProtocol = 'http';
var port = ':1234';
var address = 'localhost';
var server = browserProtocol + '://' + address;
//////////////////////////////////////////////////////////
factory.getInfoFromUrl7 = function(myUrl) {
var deferred = $q.defer();
$http.get(myUrl).success(function(data) {
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
}
return factory;
}
checkbox webpage itself
<form ng-submit="submitForm()" ng-controller="myDiagController">
<div class="control-group" style="color:black">
<label>My Checkbox</label>
<div class="checkbox">
<label class="checbox-inline" >
<input class="big-checkbox" type="checkbox" ng-model="formData.myStuff1"
ng-true-value="1" ng-false-value="0" ng-checked="formData.myStuff1 == 1">
<h4>Message 1</h4>
<input class="big-checkbox" type="checkbox" ng-model="formData.myStuff2"
ng-true-value="1" ng-false-value="0" ng-checked="formData.myStuff2 == 1">
<h4>Message 2</h4>
</label>
</div>
<br>
<input class="btn-primary" type="submit">
</form>
i did try to modify ng-checked like this and the checkbox did show checked.
ng-checked="true"
well, just used "res.json" in the node.js side and made it work, guess i just don't have time to learn, while this fxxking company gave me a tough schedule

ng-option's default ng-model value using a Factory/Service

As a new AngularJS user I have a form that populates with data as follows,
My EntriesFactory.js,
(function () {
"use strict";
var EntriesFactory = function ($http) {
var factory = {};
//Get Full List
factory.getEntries = function () {
return $http.get('ABC/XYZ.cfc?method=GetFullList&returnformat=json&queryformat=struct');
};
return factory;
};
EntriesFactory.$inject = ['$http'];
angular.module('appDHCP')
.factory('EntriesFactory', EntriesFactory);
}());
populates EntryDetails.cfm form
<form class="form-horizontal" ng-repeat="detail in entry">
<div class="form-group">
<h2 class="col-sm-2">Entry Details</h2>
</div>
</div>
<div class="form-group">
<label for="Description" class="col-sm-2 control-label">Description</label>
<div class="col-sm-4">
<input type="text" class="form-control" placeholder="{{detail.DESCRIPTION}}" value="{{detail.DESCRIPTION}}">
</div>
</div>
<div class="form-group">
<label for="Lab" class="col-sm-2 control-label">Lab/PI</label>
<div class="col-sm-4">
<select ng-model="???" ng-options="lab.LABIS for lab in labs"></select>
</div>
</div>
</form>
in here labs are retrieved from WistarService.js,
(function () {
"use strict";
var WistarService = function ($http) {
this.getLabs = function () {
return $http.get('ABC/XYZ.cfc?method=GetLabs&returnformat=json&queryformat=struct');
};
};
WistarService.$inject = ['$http'];
angular.module('appDHCP')
.service('WistarService', WistarService);
}());
Finally, here is my EntryDetailsController.js
(function () {
"use strict";
var EntryDetailsController = function ($scope, $routeParams, EntriesFactory, WistarService) {
var addressId = $routeParams.REC_ID;
$scope.entry = null;
$scope.labs = null;
//function init() {
EntriesFactory.getEntry(addressId)
.success(function (entry) {
$scope.entry = entry;
})
.error(function (data, status, headers, config) {
//handel errors
});
WistarService.getLabs()
.success(function (labs){
$scope.labs = labs;
})
.error(function (data, status, headers, config) {
//handel errors
});
/*
}
init();
*/
};
EntryDetailsController.$inject = ['$scope', '$routeParams', 'EntriesFactory', 'WistarService'];
angular.module('appDHCP')
.controller('EntryDetailsController', EntryDetailsController);
}());
What I want is, select to have {{detail.LAB}} value selected by default and have values in labs as other options.
Any help is greatly appreciated.
Once you get all the labs from service, on the scope you need to set the details.LAB variable manually which should point to an element from labs array.
WistarService.getLabs()
.success(function (labs){
$scope.labs = labs;
$scope.details.LAB= labs.filter(function(){ // some condition to filter})[0];
})
The ng-model points to details.LAB.
Update: Based on your comment the there should be some key to match labs to entry. Therefore you should do something like
$scope.details.LAB= labs.filter(function(lab){
lab.id=$scope.entry.id;
)[0];
But remember you can only do this once the entry data is available. So either chain the http operations or put a watch on entry and add that logic in the watch.

run a custom function on the click of the image insert button : Textangular

I need to override the default functionality of the image insert button of the textAngular.
I need to open a modal on the click of the same. How to do this?
I had a similar problem and found it wasn't documented super well. There are a few bug threads where some solutions are mentioned:
https://github.com/fraywing/textAngular/issues/54 and
https://github.com/fraywing/textAngular/issues/146
Following another user's solution there, and the customizing the toolbar section on the wiki, my solution looked like this:
config(['$provide',
function($provide) {
$provide.decorator('taOptions', ['taRegisterTool', '$modal', '$delegate',
function(taRegisterTool, $modal, taOptions) {
// $delegate is the taOptions we are decorating
// here we override the default toolbars specified in taOptions.
taOptions.toolbar = [
['clear', 'h1', 'h2', 'h3'],
['ul', 'ol'],
['bold', 'italics'],
['insertLink', 'insertVideo']
];
// Create our own insertImage button
taRegisterTool('customInsertImage', {
iconclass: "fa fa-picture-o",
action: function($deferred) {
var textAngular = this;
var savedSelection = rangy.saveSelection();
var modalInstance = $modal.open({
// Put a link to your template here or whatever
template: '<label>Enter the url to your image:</label><input type="text" ng-model="img.url"><button ng-click="submit()">OK</button>',
size: 'sm',
controller: ['$modalInstance', '$scope',
function($modalInstance, $scope) {
$scope.img = {
url: ''
};
$scope.submit = function() {
$modalInstance.close($scope.img.url);
};
}
]
});
modalInstance.result.then(function(imgUrl) {
rangy.restoreSelection(savedSelection);
textAngular.$editor().wrapSelection('insertImage', imgUrl);
$deferred.resolve();
});
return false;
},
});
// Now add the button to the default toolbar definition
// Note: It'll be the last button
taOptions.toolbar[3].push('customInsertImage');
return taOptions;
}
]);
}
]);
Check out the plunkr!
Major gotcha: This may be evident to others, but you need the restore selection stuff for the image insert to work. I guess execCommand puts the image at the cursor position, and that position is lost when you open up your own modal. I'm not sure if rangy specifically is necessary, or if you could just make sure the editor has cursor focus first before calling wrapSelection.
Edit: If you're importing the rangy library, textAngular has an optional method in the action constructor for it. Docs: "restoreSelection is only defined if the rangy library is included and it can be called as restoreSelection() to restore the users selection in the WYSIWYG editor." So your action method can use it instead of direct rangy calls.
action: function($deferred, restoreSelection) {
var textAngular = this;
var modalInstance = $modal.open({
....
});
modalInstance.result.then(function(imgUrl) {
restoreSelection();
textAngular.$editor().wrapSelection('insertImage', imgUrl);
$deferred.resolve();
});
return false;
},
});
...
Im' sharing the code for an image upload service I implemented through angular-bootsrap-ui $modal service and DanialFarid's angular-file-upload service.
.config(function ($provide) {
$provide.decorator('taOptions', ['taRegisterTool', '$delegate', '$modal', function (taRegisterTool, taOptions, $modal) {
taRegisterTool('uploadImage', {
iconclass: "fa fa-image",
action: function (deferred) {
$modal.open({
controller: 'UploadImageModalInstance',
templateUrl: 'views/modals/upload.html'
}).result.then(
function (result) {
document.execCommand('insertImage', true, result);
deferred.resolve();
},
function () {
deferred.resolve();
}
);
return false;
}
});
taOptions.toolbar[1].push('uploadImage');
return taOptions;
}]);
})
Now the view for the modal with the button that handles the $scope.upload() function, previews the uploaded image, and a button that fires the $scope.insert() function.
<form data-ng-submit="insert()">
<div class="modal-header">
<div class="col-md-10">
<h4 class="modal-title"><span class="glyphicon glyphicon-picture"></span> Upload Image</h4>
</div>
<div class="col-md-2 right">
<a class="close" href data-ng-click="$dismiss()"><span class="glyphicon glyphicon-remove"></span></a>
</div>
</div>
<div class="modal-body">
<img data-ng-src="{{image}}">
<progressbar data-ng-show="progress > 0 && progress < 100" class="progress-striped active" value="progress"></progressbar>
</div>
<div class="modal-footer center clearfix">
<button data-ng-click="$dismiss()" type="button" class="btn btn-default pull-left">Cancel</button>
<button type="submit" data-ng-disabled="image == null || image == '' || image == 'img/posts/default.svg'" class="btn btn-primary pull-right">Insert Image</button>
<button type="button" data-ngf-select data-ngf-change="upload()" data-ng-model="files" data-ngf-multiple="false" class="btn btn-primary pull-right"><span class="glyphicon glyphicon-picture mR5"></span>Upload Image</button>
</div>
</form>
And also the controller that handles the file upload and image insert:
app.controller('UploadImageModalInstance', function($scope, $modalInstance, Upload){
$scope.image = 'img/default.png';
$scope.progress = 0;
$scope.files = [];
$scope.upload = function(){
Upload.upload({
url: 'api/upload',
fields: {'dir': 'img/uploads/'},
file: $scope.files[0],
method: 'POST'
}).progress(function (evt) {
$scope.progress = parseInt(100.0 * evt.loaded / evt.total);
}).success(function (data) {
$scope.progress = 0;
$scope.image = data.dir+data.filename;
});
};
$scope.insert = function(){
$modalInstance.close($scope.image);
};
})

Resources