Clear ng-src using ng-click - javascript

I have problem with clear ng-src (input file) using ng-click. I would like solve this problem using angular. I tried use angular.element.val('') but this is not good solution for me. Do you know another way?
controller.js
app.imagePreview = false;
$scope.thumbnail = {
dataUrl: null
};
$scope.fileReaderSupported = window.FileReader != null;
$scope.photoChanged = function(files){
if (files != null) {
var file = files[0];
if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
$timeout(function() {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(e) {
$timeout(function(){
$scope.thumbnail.dataUrl = e.target.result;
app.imagePreview = true;
});
}
});
}
}
};
app.clearImage = function(){
$scope.thumbnail = {
dataUrl: null
};
}
index.html
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-picture-o"></i>
</div>
<input type="text" class="form-control" readonly>
<span class="input-group-btn">
<span class="btn btn-default btn-file add-img-upload">
<a id="clearPreview" type="button" ng-click="product.clearImage()">
<span class="glyphicon glyphicon-remove"></span> UsuĊ„
</a>
</span>
<span class="btn btn-default btn-file add-img-upload"><span class="glyphicon glyphicon-folder-open"></span> Wybierz
<input type="file" name="file" id="imgInp" onchange="angular.element(this).scope().photoChanged(this.files)" ng-model="files">
</span>
</span>
</div>
<img ng-if="product.imagePreview" ng-src="{{ thumbnail.dataUrl }}" id='img-upload'/>
</div>

In your controller you've named the method app.clearImage and in your html, you're calling product.clearImage. Rename one of them so that they match and it should work.
I believe you really just want clearImage to be a method of your controller. Removing "product." in front of it in your html and chanding "app." in front of it in your controller to "$scope." should also work.
in your html:
and in your controller:
$scope.clearImage = function(){
$scope.thumbnail = {
dataUrl: null
};
}

Related

AngularJS: Validators in Controller no binding with HTML side

All in-line validations in HTML side are working OK, but when I use functions in my Controller (functions ingresarNuevoEmpleador and limpiarNuevoEmpleador), always get $invalid=true. $setPristine neither works.
Apparently both sides are referencing different objects because controller functions
do not modify the state of the html side validators.
<form name="frmEmpleadorDirecto" novalidate>
<div class="row">
<div class="col-xs-8 col-sm-8">
<div class="form-group has-feedback"
ng-class="{'has-error': frmEmpleadorDirecto.nempleador.$invalid && (frmEmpleadorDirecto.nempleador.$touched || frmEmpleadorDirecto.$submitted)}">
<label for="input501">Empleador Directo</label>
<input type="text" class="form-control text-uppercase" name="nempleador" placeholder="Nombre Empleador" ng-model="objEmpleador_.nombreEmpleador_" ng-minlength="2" ng-maxlength="30" ng-required="true">
<span class="help-block" ng-if="frmEmpleadorDirecto.nempleador.$error.minlength && frmEmpleadorDirecto.nempleador.$touched">too short</span>
<span class="help-block" ng-if="frmEmpleadorDirecto.nempleador.$error.maxlength && frmEmpleadorDirecto.nempleador.$touched">too long</span>
<span class="help-block" ng-if="frmEmpleadorDirecto.nempleador.$error.required && frmEmpleadorDirecto.nempleador.$touched">required</span>
</div>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn btn-success btn-mm" ng-disabled="frmEmpleadorDirecto.$pristine || frmEmpleadorDirecto.$invalid" ng-click="ingresarNuevoEmpleador()">Aceptar</button>
<button type="button" class="btn btn-warning btn-mm" ng-click="limpiarNuevoEmpleador()">Limpiar</button>
</div>
</form>
Controller:
angular.module('BlurAdmin.pages.empleador_')
.controller('CtrlEmpleadorNuevo',CtrlEmpleadorNuevo);
function CtrlEmpleadorNuevo($scope,$http,$rootScope) {
$scope.objEmpleador_ = new eva.Empleador_();
$scope.ingresarNuevoEmpleador = function()
{
console.log("Nombre: " + $scope.objEmpleador_.nombreEmpleador_); //OK
if($scope.objEmpleador_.$valid) //always invalid
{
console.log('valid!');
}else {
console.log('invalid!'); }
}
$scope.limpiarNuevoEmpleador = function ()
{
$scope.objEmpleador_.$setPristine; //no changes
$scope.objEmpleador_.nombreEmpleador_ = ''; //Works: reset html field
}
}
Objects:
eva.Empleador_ = function() {
var self = this;
self.nombreEmpleador_ = '';
};
Your form is bound on your $scope and inputs and their validity can be reached following the name attribute.
$scope.ingresarNuevoEmpleador = function(){
console.log("Nombre: " + $scope.objEmpleador_.nombreEmpleador_); //OK
if($scope.frmEmpleadorDirecto.nempleador.$valid) {
console.log('valid!');
}else {
console.log('invalid!');
}
};
Plunker

ng-model doesnt bind with text field

Consider the following JS
angular.module('myApp')
.controller('HeaderCtrl', function($scope) {
$scope.searchBooking = "test";
$scope.goToBooking = function() {
console.log($scope.searchBooking);
//$location.path('/bookings/' + $scope.searchBooking);
//delete($scope.searchBooking);
}
$scope.printValue = function() {
console.log($scope.searchBooking);
}
}
);
And the following HTML
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Testing" ng-model="searchBooking" ng-change="printValue()">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
My problem is that when the page loads, "test" is written in the text field, but when I change the field or press the button, nothing happens (console says "test" on every change or button click. Anyone know what I did wrong?
Try to wrap the value in an object. Objects are passed by reference, but simple values are passed as a copy of that value. It happened to me too several times.
Try this approach
$scope.myObject.searchBooking = "test"
So the full code will look like this
angular.module('myApp')
.controller('HeaderCtrl', function($scope) {
$scope.myObject.searchBooking = "test";
$scope.goToBooking = function() {
console.log($scope.myObject.searchBooking);
//$location.path('/bookings/' + $scope.myObject.searchBooking);
//delete($scope.myObject.searchBooking);
}
$scope.printValue = function() {
console.log($scope.myObject.searchBooking);
}
}
);
and the html
<input type="text" class="form-control" placeholder="Testing" ng-model="myObject.searchBooking" ng-change="printValue()">
Find this fiddle which is having ng-model binding in ng-change.
HTML
<div ng-controller="MyCtrl">
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Testing" ng-model="searchBooking" ng-change="printValue()">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</div>
Angular controller
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.searchBooking = "test";
$scope.goToBooking = function() {
console.log($scope.searchBooking);
//$location.path('/bookings/' + $scope.searchBooking);
//delete($scope.searchBooking);
}
$scope.printValue = function() {
console.log($scope.searchBooking);
}
}

jQuery keep other boxes not edited state

In the code below when I click edit the other boxes loose the edited icon until cancel is clicked.
Is there away that I can have it so that if a box is not being edited it keeps the normal state of code?
The library I am using is: https://vitalets.github.io/x-editable/
Normal State:
When an edit button is clicked:
jQuery:
/* X-Editable */
$(function(){
$.fn.editable.defaults.mode = 'inline';
$.fn.editable.defaults.params = function (params) {
params._token = $("#_token").data("token");
return params;
};
var dataURL = $('.updateField').data('url');
var inputName = $('.updateField').attr("name");
$('.updateField').editable({
type: 'text',
url: dataURL,
name: inputName,
placement: 'top',
title: 'Enter public name',
toggle:'manual',
send:'always',
ajaxOptions:{
dataType: 'json'
}
});
$('.edit').click(function(e){
var container = $(this).closest('.input-group'); // !!
var input = container.find('.updateField');
var inputName = input.attr('name');
var dataURL = input.data('url');
console.log(inputName);
e.stopPropagation();
container.find('.updateField').editable('toggle'); // !!
container.find('.edit').hide(); // !!
});
$(document).on('click', '.editable-cancel, .editable-submit', function(e){
$(e.target).closest('.input-group').find('.edit').show(); // !!
})
//ajax emulation. Type "err" to see error message
$.mockjax({
url: '/post',
responseTime: 100,
response: function(settings) {
if(settings.data.value == 'err') {
this.status = 500;
this.responseText = 'Validation error!';
} else {
this.responseText = '';
}
}
});
});
Normal State HTML:
<input name="__RequestVerificationToken" type="hidden" value="{{ csrf_token() }}" />
<div class="box-body">
<div class="form-group">
<label class="col-sm-2 control-label" for="siteName">Website Name</label>
<div class="col-sm-3">
<div class="input-group">
<input class="form-control updateField" data-url="{{ route('generalDataSubmit', 1)}}" data-title="Website Name" name="siteName" placeholder="Email" type="input" value="{{ old('siteName', $siteSettingsData->siteName)}}"> <span class="input-group-btn"><button class="btn btn-default edit" type="button"><span class="glyphicon glyphicon glyphicon-pencil"></span></button></span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="siteEmail">Website E-Mail Address</label>
<div class="col-sm-3">
<div class="input-group">
<input class="form-control updateField" data-url="{{ route('generalDataSubmit', 1) }}"data-title="Website E-Mail Address" name="siteEmail" placeholder="Site E-Mail" type="email" value="{{ old('siteEmail', $siteSettingsData->siteEmail) }}"> <span class="input-group-btn"><button class="btn btn-default edit" type="button"><span class="glyphicon glyphicon glyphicon-pencil"></span></button></span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="siteCopyright">Website Copyright</label>
<div class="col-sm-3">
<div class="input-group">
<input class="form-control updateField" data-url="{{ route('generalDataSubmit', 1)}}" data-title="Website Copyright" name="siteCopyright" placeholder="Site Copyright" type="input" value="{{ old('siteCopyright', $siteSettingsData->siteCopyright)}}"> <span class="input-group-btn"><button class="btn btn-default edit" type="button"><span class="glyphicon glyphicon glyphicon-pencil"></span></button></span>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
try changing the following line:
container.find('.edit').hide();
to
$(this).hide();
It seems like you are using some bootstrap design template.From my point of view the code
$('.edit').click(function(e){
var container = $(this).closest('.input-group'); // !!
var input = container.find('.updateField');
var inputName = input.attr('name');
var dataURL = input.data('url');
console.log(inputName);
e.stopPropagation();
container.find('.updateField').editable('toggle'); // !!
container.find('.edit').hide(); // !!
});
seems ok.I don't understand the line container.find('.updateField').editable('toggle'); // !! in the function.Are you using some kind of library. My suggestion is to remove that line from your code and test.Also check whether you are getting the correct value of inputName outputted.And finally check in the console for any errors when you click the edit button.
Try using $(e) instead of $(this) in the following code:
$('.edit').click(function(e){
//var container = $(this).closest('.input-group');
var container = $(e).closest('.input-group');
var input = container.find('.updateField');
var inputName = input.attr('name');
var dataURL = input.data('url');
console.log(inputName);
e.stopPropagation();
container.find('.updateField').editable('toggle'); // !!
container.find('.edit').hide(); // !!
});

How can I fix this Angular $scope issue?

I have a partial that uses one controller called CaseNotesCtrl. I am having problems accessing $scope variables inside of this partial. The code is this:
<div class="row" ng-show="$parent.loggedin" ng-controller="CaseNotesCtrl">
<div class="col-sm-12 note
-field" ng-show="$parent.addingNote">
<label for="noteEntry">Enter your note</label>
<textarea class="form-control" name="noteEntry" rows="4" ng-model="newNote.note"></textarea>
<br />
</span>
<a href="" data-toggle="tooltip" data-placement="top" title="Cancel Adding Note" class="btn btn-xs btn-danger calicon-view note-cancel-button" ng-click="$parent.cancelNote();" tooltip>
<span class="glyphicon glyphicon-remove-sign"></span>
</a>
</div>
<div class="col-sm-12">
<a href="" data-toggle="tooltip" data-placement="top" title="Add a Note" class="btn btn-xs btn-danger calicon-view note-add-button" ng-click="$parent.addNote();" ng-show="!$parent.addingNote" tooltip>
<span class="glyphicon glyphicon-list-alt"></span>
</a>
</div>
<div class="col-sm-12 note-list-heading" ng-repeat-start="note in caseNotes">
<span class="note-header">Note entered by {{ note.User.DisplayName }} and was last edited on {{ note.ModifiedDate | date: "MM/dd/yyyy 'at' h:mma" }}</span></span>
</div>
<div class="col-sm-12 note-text">
{{ note.Notes }}
</div>
<div ng-repeat-end></div>
</div>
here is the controller code:
JBenchApp.controller('CaseNotesCtrl', ['$scope', '$http', '$routeParams', 'HoldState', function ($scope, $http, $routeParams, HoldState) {
// Management of case notes
$scope.NotesCaseID = $routeParams.number;
$scope.NotesUserName = localStorage.getItem('UserName');
$scope.NotesUserRole = localStorage.getItem('UserRole');
$scope.addingNote = false;
$scope.newNote = { note: 'Testing 123', CaseID: 0, NoteID: 0 };
$scope.getCaseNotes = function (CaseID, UserName, UserRole) {
$http.get('http://10.34.34.46/BenchViewServices/api/CaseNote/' + CaseID + "/" + UserRole + "/" + UserName).success(function (response) {
$scope.caseNotes = response;
})
};
$scope.saveCaseNotes = function (CaseID, UserName, NoteID) {
$scope.addingNote = false;
};
$scope.addNote = function () {
$scope.addingNote = true;
};
$scope.cancelNote = function () {
$scope.newNote.note = '';
$scope.addingNote = false;
};
$scope.editNote = function(caseID, noteID, noteText){
$scope.newNote.note = noteText;
$scope.newNote.CaseID = caseID;
$scope.newNote.NoteID = noteID;
$scope.addingNote = true;
$parent.addingNote = true;
};
$scope.getCaseNotes($scope.NotesCaseID, $scope.NotesUserName, $scope.NotesUserRole);
}]);
As you can see I am having to use $parent in places such as $parent.addingNote. If I change that to $scope.addingNote the function isn't called. The only place I am OK with $parent is $parent.isLoggedIn. How can I fix this so that it just uses $scope?
I would suggest you to use the AngularJS "Controller as" syntax when using ng-controller.
In this case it would be something like this:
app.controller('CaseNotesCtrl', function () {
this.title = 'Some title';
});
<div ng-controller="CaseNotesCtrl as caseNotes">
{{ caseNotes.title }}
</div>
So you it would be easy to you to know which scope are you working with.

Adding Angular UI Datepicker dynamically

In my project I need to add dynamic amount of datepickers to the page.
I tried to do it this way (Plunker):
Script:
var app = angular.module('plunker', ['ui.bootstrap']);
app.controller('MainCtrl', function($scope) {
$scope.openDatePicker = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: "yy",
startingDay: 1,
format: "shortDate"
};
$scope.details = [{
"parameterValue": "2015-08-12"
}, {
"parameterValue": "2015-08-12"
}, {
"parameterValue": "2015-08-12"
}, {
"parameterValue": "2015-08-12"
}];
});
HTML:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="script.js"></script>
</head>
<body>
<div ng-controller="MainCtrl">
<form name="detailsForm" novalidate ng-submit="submitForm(detailsForm.$valid)">
<div ng-repeat="item in details" class="input-group">
<input ng-model="item.parameterValue" type="text" class="form-control" id="datePickerItem" datepicker-popup="shortDate"
is-open="opened" datepicker-options="dateOptions" current-text="Today" clear-text="Clear" close-text="Close" ng-readonly="false" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="openDatePicker($event)"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</div>
</form>
</div>
</body>
</html>
The problem is that when I try to open one datepicker, all of them are opened (logically, as they share the same $scope.opened variable). Also when I close them and try to open them again, nothing happens.
Is there a elegant way to achieve this?
Thanks.
All of your datepickers have id="datePickerItem".
The id attribute must be unique in html. Try this instead:
id="datePickerItem_{{$index}}"
This will add the ng-repeat's current index to the id, so you can be relatively certain your id's are unique. This should also prevent all the datepickers from opening at the same time.
Also, you're using one and the same opened variable for all datepickers.
Try this instead:
<div ng-repeat="item in details" class="input-group">
<input ng-model="item.parameterValue" type="text" class="form-control"
id="datePickerItem_{{$index}}" datepicker-popup="shortDate"
is-open="opened[$index]" datepicker-options="dateOptions" current-text="Today"
clear-text="Clear" close-text="Close" ng-readonly="false" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="openDatePicker($event, $index)">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
</div>
And:
$scope.opened = [];
$scope.openDatePicker = function($event, index) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened[index] = true;
};
Just make sure you set $scope.opened[index] to false, in case you close the datepicker.
try this:
$scope.open = function($event,opened) {
$event.preventDefault();
$event.stopPropagation();
$scope[opened] = true;
};
and in your html
ng-click="open($event, 'nameOfYourModel')"
why not bind opened on the repeat object?
like:
<div ng-repeat="item in details" class="input-group">
<input ng-model="item.parameterValue" type="text" class="form-control"
id="datePickerItem_{{$index}}" datepicker-popup="shortDate"
is-open="item['opened']" datepicker-options="dateOptions" current-text="Today"
clear-text="Clear" close-text="Close" ng-readonly="false" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="openDatePicker($event, item)">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
and in controller:
$scope.openDatePicker = function($event, item) {
$event.preventDefault();
$event.stopPropagation();
if(item.opened){
item.opened = !item.opened;
} else{
item.opened = true;
}
};

Categories