Binding ng-click argument object keys to scope properties? - angularjs

I'm trying to pass an object with variable keys to an ng-click method. In regular javascript you would just do this:
var x = "fork";
var obj = {};
obj[x] = "three points" //{ fork: "three points" }
Normally to send objects via ng-click you would set up an object literal as the argument.
//in controller
$scope.val = "red";
//in view
<button ng-click="click( { item: val} )"></button>
//output is { item: "red" }
But what if you want the key of the argument's object to be bound to a scope property?
//in controller
$scope.key = 29845;
//in view
<button ng-click="click( { {{key}}: 456 } )"></button>
//should output { 29845: 456 }
Trying this results in a syntax error. However, you can use this same syntax in ui.bootstrap typeahead's typeahead-on-select method and it works... I have no idea why though.
<input type="text"
typeahead="i for i in data"
typeahead-on-select="select( { {{i}}: 'something' } )"
class="typeahead" />
http://plnkr.co/edit/EfSvbP8fXBLoZhr8eWG5
How can you bind scope properties to object keys?

You can try something like this :
<button ng-click="temp={};temp[key]=456;click(temp)"></button>
See http://plnkr.co/edit/NfH3xNUXtBROiu9olHVE?p=preview.
Though it will add temp variable in the scope.

Related

AngularJs Component doesn't update view after img loading

i'm using angularJs 1.7 components.
This is my component who uploads a picture then converts it to base 64, then it is supposed to display it, but the displaying doesnt work .
myApp.component('club', {
templateUrl: 'vues/club.html',
controller: function($log,$scope) {
// HTML form data, 2 way binding ..
this.club = {};
// Bse 64 encoder
encodeImageFileAsURL = function() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: convert base64 : OK
this.club.img = srcData ; // Displaying in view doesnt work
}
fileReader.readAsDataURL(fileToLoad);
}
}
// Jquery watcher when we upload a picture
$(document).on('change', 'input[type="file"]' , function(){
encodeImageFileAsURL();
});
This is the html button inside the template :
<div id="upload_button">
<label>
<input name="inputFileToLoad" id="inputFileToLoad" ng-model="logo" type="file" onchange="" /> </input>
<span class="btn btn-primary">Upload picture</span>
</label>
</div>
This is the error :
TypeError: this.club is undefined
srcData is ok, and holds a base 64 image, the function works well.
I've tried the solution provided (.bind(this)) there with no luck , i dont know where to place it:
How to access the correct `this` inside a callback?
When using the $scope syntax, it is working, adding $scope.$apply(), but now i'm using components based dev, and the .this syntax, it doesnt work any more .
EDIT 1 :
Ok, i've initialized club with
$scope.club = {} ;
then inside the function, i'm writing
$scope.club.img = srcData ;
Then, it is working ok. I dont understand why .this is not the same than $scope !
See following example for where this object has reference to
a={
firstname:"something",
lastname:"something2",
fullname:function(){
console.log(this.firstname+' '+this.lastname);
}
}
a.fullname();
In above example Object a is created and inside fullname() function this object pointing to 'a' Object.
So that in your case
templateUrl is only variable on this Object if you do not want to use $scope. You can declare it by using var club = {}

ES6 class calling a method within a class with bind vs call?

I have a class written in ES6 and I have a directive "action" which needs to access a controller value called "selected". This controller value "selected" is updated by another directive "grid". ( 2 way binding)
I need to pass "selected" value from the controller that has been updated by Directive "grid" to Directive "actions" on-select . I have tried to pass by doing a "bind" but i get an type error as "cannot read actionHandler of undefined"
I am not sure what is the best way to handle this , such that when the "selected" value has been updated by the "grid" directive, the actionEvent is triggered with the updated value from the controller. The directives are working correctly and i am able to see that it breaks on breakpoints.
Here is what i have in HTML
<div class="col-xs-9">
<action options="ctrl.Actions" on-select="ctrl.actionEvent">
</action>
</div>
<div class="col-xs-12">
<grid config="ctrl.gridOptions" data="ctrl.data" selected="ctrl.selected"></grid>
</div>
In the Controller,
class CheckC {
constructor($scope) {
this.$scope = $scope;
this.selected = this.$scope.selected;
}
actionEvent() {
this.actionHandler.bind(this);
}
actionHandler(item, event) {
let selection;
let model = this.selected;
if(model) {
item.id = 1;
}
}
}
First of all, don't be confused between .bind() and .call().
First returns a new function instance, that can be called later, but with preserved this.
Second calls function immediately, but modifies context of this only for this call.
Read this answer for more information
You are passing a reference to actionEvent method. At the moment of call, the reference to original controller object is already lost.
To preserve the reference, you need to save it first in constructor
class CheckC {
constructor($scope) {
this.$scope = $scope;
this.selected = this.$scope.selected;
//bind method here
this.actionEvent = this.actionEvent.bind(this);
}
actionEvent(item, event) {
// this here will be always contain a referene to class instance
this.actionHandler(item, event);
}
actionHandler(item, event) {
let selection;
let model = this.selected;
if(model) {
item.id = 1;
}
}
}
Also in your code actionEvent method seems redundant. Consider to recfactor code and pass actionHandler directly. (Bu don't forget to update .bind() call, it should bind actionHandler after).

angular-dialog-service update parent scope data object

I've a template:
<p class="text-right">
<a ng-click="editTherapeuticProposal(meow.accepted_tp)" class="fa fa-pencil"></a>
</p>
which calls the editTherapeuticProposal function defined in its controller, passing it the meow.accepted_tp object (here I use angular-dialog-service: https://github.com/m-e-conroy/angular-dialog-service):
// here tp is equal to meow.accepted_tp
$scope.editTherapeuticProposal = function(tp) {
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tp: tp}, { copy: false });
};
tp is an object.
Then in the dialog controller I display a form in order to let the user modify tp. I do some stuff, the relevant ones are:
// data is the object received by the dialog controller: {scope: $scope, tp: tp}
if(typeof data.tp != 'undefined') {
$scope.therapeuticProposal = angular.copy(data.tp);
}
I copy the object to work on a different object (I don't want data to be updated if not saved)
When pressing the save button in the dialog, the following function runs:
var complete = function(tp) {
data.tp = tp;
//...
}
Ok, the problem is that meow.accepted_tp in the parent scope doesn't get updated. If I do
var complete = function(tp) {
data.tp.title = 'meow';
//...
}
Its title gets updated. There is clearly something wrong with the prototypal inheritance, I know that in order to get variables updated they should be properties of an object, but tp is already passed as an object property (of the data object). Any ideas?
Edit
After re-reading the angular-dialog-service docs, you can pass a result back using modalInstance. It sounds like this is what you want to do.
The reason your binding isn't working is because you're changing the object reference from a child scope, rather than a property on the object bound (which is why data.tp.title = 'meow' works).
Anyway, for your case, try this:
// here tp is equal to meow.accepted_tp
$scope.editTherapeuticProposal = function(tp) {
var dlg = dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, data: data}, { copy: false });
dlg.result.then(function(tp) {
// Get the result and update meow.accept_tp
$scope.meow.accepted_tp = tp;
});
};
Then in the dialog, when you complete, do:
var complete = function(tp) {
$modalInstance.close(tp);
}
For an example, see http://codepen.io/m-e-conroy/pen/rkIqv, in particular the customDialogCtrl (not customDialogCtrl2) is what you want.

Firebase $save doesn't work inside an event handler function

I must be missing something really basic. I have an input box where the list name is entered. The name is then saved to the Firebase.
When using $watch, it works just fine. However, if done through ng-keyup event, it returns the following error
TypeError: undefined is not a function.
What am I missing?
HTML:
<input id="which_list" ng-keyup="enterThis($event)" ng-model="which_list.name" >{{which_list.name}}</span>
Controller:
$scope.which_list = sync.$asObject();
$scope.$watch('which_list.name', function() {
gDataService.which_list.name= $scope.which_list.name;
$scope.which_list.$save() // THIS WORKS
// $scope.which_list => d {$$conf: Object, $id: "id", $priority: null, name: "to1_list", $save: function…}
.then(function(){
console.log($scope.which_list.name);
});
});
$scope.enterThis = function(event){
if (event.keyCode === 13) {
gDataService.which_list.name= $scope.which_list.name;
$scope.which_list.$save(); // THIS DOESN't WORK
// $scope.which_list = Object {name:"list_name"}
}
};
EDIT: In the comment, I included the value of $scope.which_list shown at the breakpoint.
Currently as you are changing in scope which_list converting to plain old JavaScript objects (POJO), I believe you need to unable 3 way binding between scope variable and $asObject().
Code
var which_list = sync.$asObject();
// set up 3-way data-binding
which_list.$bindTo($scope, "which_list");
Update
Also as you are using $scope.which_list object which contains name and other property,So do initialize it on starting of your controller like
$scope.which_list = {}
Hope this could help you, Thanks.

How can I pass a parameter to an ng-click function?

I have a function in my controller that looks like the following:
AngularJS:
$scope.toggleClass = function(class){
$scope.class = !$scope.class;
}
I want to keep it general by passing the name of the class that I want to toggle:
<div class="myClass">stuff</div>
<div ng-click="toggleClass(myClass)"></div>
But myClass is not being passed to the angular function. How can I get this to work? The above code works if I write it like this:
$scope.toggleClass = function(){
$scope.myClass = !$scope.myClass;
}
But, this is obviously not general. I don't want to hard-code in the class named myClass.
In the function
$scope.toggleClass = function(class){
$scope.class = !$scope.class;
}
$scope.class doesn't have anything to do with the paramter class. It's literally a property on $scope called class. If you want to access the property on $scope that is identified by the variable class, you'll need to use the array-style accessor:
$scope.toggleClass = function(class){
$scope[class] = !$scope[class];
}
Note that this is not Angular specific; this is just how JavaScript works. Take the following example:
> var obj = { a: 1, b: 2 }
> var a = 'b'
> obj.a
1
> obj[a] // the same as saying: obj['b']
2
Also, the code
<div ng-click="toggleClass(myClass)"></div>
makes the assumption that there is a variable on your scope, e.g. $scope.myClass that evaluates to a string that has the name of the property you want to access. If you literally want to pass in the string myClass, you'd need
<div ng-click="toggleClass('myClass')"></div>
The example doesn't make it super clear which you're looking for (since there is a class named myClass on the top div).

Resources