indexOf for angular typescript - javascript

I am trying to write a similar true/false statement, Similar to how the .selected() method would work in Angular typescript.
The idea is to show an image if the calculation or *ngIf statement evaluates to True. The code is written in the app.html side
Code:
<img src="/project/x.png" *ngIf="selectedimage.indexOf(v) !== -1"><a href="{{i['link']}}" target="blank" (click)="update_viewed(z)">
There is a *ngFor statement right before this code, with ;let z = index at the end. The overall code creates a # of rows dynamically depending on how many elements exist in an array. (code not provided for this here.) Then, if the user clicks on the href link, the index value is passed into a method, which pushes it to an array. in console.log(this.selectedimage) I can see the values being added in each time I click the href reference. Not sure why the ngIf logic isn't working.
All help much appreciated.

You cannot use indexOf with *ngIf on the template, I would recommend you to create a function that returns true/false based on the logic. Use indexOf within the function and call it with *ngIf

Related

Angular 4 Binding function in template file

I need to check some condition in angular. So I use the following method.
<span> {{checkValue("test")}} </span>
Then My component like
checkValue(val){
if ("test" == val){
return "value is true"
}
}
in this case the function call continuously.
Is this correct method or suggest me any other idea. Thanks in advance.
The code in you example is perfectly valid, function will be triggered at every change detection pass, there must be something else that triggers change detection i.e. setInterval, http calls and so on.
As #trichetriche mentioned
Binding a variable to a template means that at every lifecycle step,
Angular will check this variable. In the case of a function, it will
call it. You can't stop that (for all I know), and you should not,
otherwise Angular will stop checking for changes on your variables.
You should avoid doing this. I believe you should try find the best solution before doing this.
In your case you can check this in html itself. So it will return true or false.
Try this
<span *ngIf="val =="test""> value is true </span>

Botpress concatenate variable, as argument, in execute code action form

I know if I pass {{variable}} (like a {{event.text}}) in args field of action form works fine.
But, when I try concatenate this variable with a another String, this not work.
Result in {{state.api_url}}/users string, and I need http//myapi.com/users
Is it possible?
I may have an extremely kludgy workaround for this based on bad javascript.
I was looking to iterate a temp variable downwards. I did the assignment in the raw code box for a transition
Good code like temp.variable==1 would be a true/false test.
But just using one equals sign performs the assignment.
So temp.variable=temp.variable-1 in the raw code box subtracted one from my (numeric value) variable.
This seems to return False for the purposes of the transition so it doesn't matter where you point it as long as it's in the chain.
It seems to work for me, anyway.
I'm properly not sure what your code would look like, perhaps you make a new variable then do a transition with
temp.variable_you_just_made=state.api_url+'/users'
then call that variable doing your url thing?
[Looking around I come to suspect the correct thing would be to make a new action https://botpress.io/docs/10.0/getting_started/trivia_actions/ but I am new to all this]

Angular JS: ng-include by function

I am having strange experience while using ng-include. I am trying to get template path by triggering a function defined in controller which is returning path as per parameter passed. Here is my code-
<tr ng-repeat="detail in Ctrl.details" ng-include="Ctrl.getTemplate(object)"></tr>
Contoller-
self.getTemplate = function (obj) {
if (<condition>) {
return 'view1';
} else return 'view2';
};
This is working really fine, but I observed really strange behavior while debugging the code. In my table row I am having 3 buttons and I applied Bootstrap tooltip on them. Whenever I hover them tooltip comes up & on mouse left getTemplate() gets called. Do anybody know why this is happening?
This is expected behaviour.
Have a look at this article. Angular needs to check whether the expression for ng-include has changed or not. In order to do that it needs to evaluate Ctrl.getTemplate(object) on every digest loop because there's no other way to find out whether its return value has changed and therefore it needs to pass a new value to ng-include.

Check if params was passed or not

I have this Javascript function which i use to append elements do my form. When the form is submitted, all elements are passed in as params.
Here's the problem. The elements that my function appends are part of a Hash. This basically works as the rails "nested-attributes".
All seems to be working fine, except when one of the "Hashs" is empty. When i delete all elements from the collection, the hash params is not passed to the controller.
Example (Imagine i appended Honda, Toyota, Hyundai using my JS function)
Cars
[Honda]
[Toyota]
[Hyundai]
This is how the hash is set up in the JS function (every time i click the "add"):
CarsHash.name= "cars_hash"+"["+"tmp_cars"+"]"+"["+i+"]"+"car_name"
If i were to submit the form, the values would be passed as Hash to the controller like this:
cars_hash=>{tmp_cars=>"{"1"=>{car_brand=> "honda"},"2"=>{car_brand=> "toyoda"},"3"=>{car_brand=> "hyundai"}"}
However, if i decide to delete all those values from the hash (using the delete button which also has functionality stated on the JS function) and submit the form, the Hash is not even present as a param. Then, when i get to my controller and i try to populate the variable i use for iterating/inserting into my DB:
Controller
cars_hash = params[:cars_hash][tmp_cars]
It gives me this error:
undefined method `[]' for nil:NilClass
I understand, the param is not even present so its essentially nil. I tried with all this possibly options:
if not params[:cars]["tmp_cars"].blank?
if not params[:cars]["tmp_cars"].empty?
if params[:cars]["tmp_cars"].present?
if params[:cars]["tmp_cars"] != nil
But no luck. Can anyone suggest me a way to get this to work? Again, the param will only be not nil IF the hash as a value. For it to have a value, an element must be appended to the document through the JS function.
Try doing:
cars_hash = params[:cars_hash] && params[:cars_hash][tmp_cars]
I would strongly recommend installling andand gem which is perfect for situations like this. With this gem you can wirte the code above like:
cars_hash = params[:cars_hash].andand[tmp_cars]
UPDATE:
Your code was not working because params[:cars_hash] returned nil, on which you were trying to call [] method, and such a method is not defined for nil object. Hence you need to check whether params[:cars_hash] is nil or not before you call anything on it.
&& operator have this nice property that it is not even executing the right argument whan the left argument is falsy - there is no point of doing this. Since every expression in ruby returns value of the last executed command, && returns whatever left expression returns if it is falsy (false or nil) and otherwise it runs the expression on its right side and returns its value. This is pretty common to use this && in this context in Ruby.

live function with out arguments in jQuery

I wanna select some item by jQuery which has been added after loading page,so I wanna use live() function.I used it before for clicking like following code:
$("selector").live('click')
but now when I wanna use it in another function.
but It will not work with out argument,like it live()
for e.g followin code will alert test (work)
var pos_eq=Math.abs($('.myList').css("left").replace("px","")/$('.myList').children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");
but this will not.
var pos_eq=Math.abs($('.myList').live().css("left").replace("px","")/$('.myList').live().children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");
how can I solve it?
You want a function, not a variable. It looks like you are trying to keep pos_eq up to date after elements have been added to the page. Having a variable auto-update when the DOM changes in the way you are trying to do is not possible with JavaScript. What you can do is use a function instead of a variable. This way whenever the value is accessed you are getting the latest value because it is computed on demand:
function pos_eq() {
var list = $('.myList');
var left = parseInt(list.css("left"));
var width = parseInt(list.children('li').eq(0).css('width'));
return Math.abs(left / width) + 1;
}
I broke your code up into multiple statements to make it more readable. You would use this function the same as you used the variable, but instead add parens to the end to invoke the function:
alert(pos_eq);
alert(pos_eq());
To get a set of objects at the time you need them, just do $("selector"). That will do a query at that time and get the set of objects. There is no need to use .live() in order to query objects on the page. It does not matter whether the objects were part of the original page or were added dynamically later. When you do $("selector"), it will search the contents of the current page and get you the objects that are currently in the page that match the selector.
There is no way to do a live selector query and save it and have it automatically update in jQuery or any other library I know of. The way you solve that issue with a dynamic page is that you just do a new query when you need current results.
The description of live() is: Attach a handler to the event for all elements which match the current selector, now and in the future. It does not give you a live node list despite its name. jQuery does not have any method that returns a live node list(such as those returned by getElementsByTagName etc.) as far as I know.

Categories

Resources