Gotcha with ng-model inside ng-if

It’s been written clearly in the angular.js official document but still it confused us in an instance. If you’re reading the documentation of ng-if, pay extra attention to the following paragraph

The scope created within ngIf inherits from its parent scope using prototypal inheritance. An important implication of this is if ngModel is used within ngIf to bind to a javascript primitive defined in the parent scope. In this case any modifications made to the variable within the child scope will override (hide) the value in the parent scope.

We had a template structure as follows

<div class="container">
  <h3>{{title}}
  <div ng-if="metadata">
     <h4>Add Category</h4>
     <input type="text" ng-model="categoryValue" />
     <button ng-click="addCategory">Add</button>
  </div>
</div>

In our scope, we properly add title property and addCategory method. Whenever, we click the ‘Add’ button it goes to correct method. However, inside our addCategory method value of $scope.categoryValue is always undefined.

It took us a while to figure out the issue. However, when we figured it completely made sense. The issue is simple and very straightforward.

The block where we’ve used ng-if, a child scope (parent is the scope we had title property, addCategory method) is being created. When we click the addCategory button, being prototypal inheritance, it finds the method inside the child scope. Obviously, the method isn’t there because we didn’t define the method in this scope. So the lookup goes up to the parent. The method is there. So addCategory method is invoked from the parent scope and categoryValue is undefined.

In the child scope, when we’ve used categoryValue, the value will be looked up in the current scope, parent scope and any other ancestor scopes. It’s nowhere! But when we write something there a property in the local scope (child scope that created for ng-if) is created and the value is saved there. So our illustration is like

$parentScope.addCategory

$childScope.categoryValue

Inside the addCategory method, it is looking for categoryValue but unfortunately it is defined that scope’s child scope. Lookup is always upward, never downward.

 

There are a number of solutions to this problem.

1) Replace ng-if with ng-show.

2) If you require to have ng-if, pass the model’s along with method invocation.

<button ng-click="addCategory(categoryValue)">Add</button>

So now the value of categoryValue from current scope will always be passed to the method during invocation and the method just have to accept that as an argument to get the value. Rather than finding the value in the scope, it should just use the passed argument.

Exploring NY – part 2

This is continuation of last post where I’m trying to write my random experiences in New York.

Boishaki Utshob (Bangla New Year) Celebration

Pohela Boishak 1421

Pohela Boishak 1421

This was my first Bangla New Year celebration outside of Bangladesh though I rarely joined mass gathering in this day. In addition to girls, usually boys also take some preparations for celebrating this day. However, as usual, I hate preparations; specially with clothing :P. On the day (April 14, 2014) My wife & her friends (with their family), sister-in-law and her friend and me all headed for Jackson Heights where, I heard, most of the Bengali people join on this day.

We didn’t get the parking around, even a few blocks away, the main gather spot. So we decided to head for the NTV Bhaban (NYC office of a Bangladesh TV channel) where cultural programs happens. We really enjoyed the time there from live songs, Bangladeshi (and/or Indian) foods like Fushka, Chotpoti, Pitha, Jhalmuri etc.

Highland Park, Brooklyn

Highland Park, Brooklyn

Highland Park, Brooklyn

It was my another lone cycle exploring. I, initially, planned to go to Forest Park. On the way to Forest Park, I found this park and thought it’s worth exploring. Above the ground level, it has nice bike lane surrounding a lake (though seemed restricted to public).

Randall’s Island Park

Raita at Randall’s Island Park

Over a weekend we, friends and family, went to Randall’s Island park without any plan. I don’t remember the name of the place we initially planned to go but ended up going to this park and, most importantly, we never regret that :). The weather and the lights were stunning but again, unfortunately, my camera wasn’t with me. However, that didn’t stop us enjoying the beauty of the island and the park itself. Then we all sat and relaxed on the sport field. The kid, Raita, of our friend enjoyed the moment too.

To be continued…

Exploring NY – part 1

It’s been more than 3 months since I came to New York. As I joined my workplace within 2 days after coming here and being my wife unable to move easily and frequently due to her pregnancy, I didn’t get enough chances to go out; specially far. However, my explorer mind kept pushing me to go and look nearby.

My $99 bike from Walmart

My $99 bike from Walmart

The first great thing I did was that I bought was a bicycle from Walmart. Though I had plan to buy little expensive bike (something lightweight with aluminum frame), I ended up buying a cheap bike as everyone was warning that the area I live in is little risky and theft prune for expensive bikes(, and, unfortunately, they are right as someone already tried to steal this bike :(). Though I said cheap; it’s a very good bike and looks great. No one ever thinks that this is so cheap. Everyone I asked to guess the price; they ended up guessing about $300-$400 but actual price is $99 (I assembled it myself). My bike was my companion for all of my not-so-lone adventures.

Gateway Drive

My first lone adventure was Spring Park (not sure if name is correct), north of Belt Pkwy and opposite of Gateway Center. At that time snows were just started to go away but it was still cold resulting almost no people in the park. It was me, my bike and another mom with her child playing alone.

Spring Park, Gateway Dr.

Spring Park, Gateway Dr.

However, the cleanliness and the softness of the park just overwhelmed me. I was just thinking, how beautiful this will be when everything becomes green here. I didn’t feel alone there though no human being was with me. I was feeling just natural. I passed sometime there sitting on the bench, taking a few pictures, pumping my bike, watching birds flying, seeing the high lands on the other side, cars moving so fast outside of the park.

Seeing the highland on the other side, I was thinking the beach is nearby and attempted to go there. As I didn’t notice the bike lane that time I couldn’t go there using those high speed routes which is not legal. I kept that adventure for next time and decided to study the routes in detail before of that. However, I discovered the bike routes to beach in the same day evening when one of friend drove car through Belt Pkwy.

Time Square

Time Square

Times Square

I visited Time Square in 42nd Street with my wife and a her friend’s family. Though I liked the brightness and colorful moments there; I was just unable to figure out whether do people come here to see these ads in televisions or something else (other than eve of new year)?

The Hudson River

I love Friday in New York. There are many reasons. It’s a jummah day. It’s a last workday before weekend. On friday our office provides catered lunch which is, almost, always great :). Finally, friday evening my wife comes to my workplace and, after work, we go somewhere and return home late. So far I remember, Hudson River was the first place we conquered together. At that time our office was in W 24th Street.

The Hudson River

The Hudson River

It wasn’t far from our work. We walked together to the bank of The Hudson River from our office. I must mention one name of my co-worker here. It’s Brian Schmitz. Brian and I often run after the work. Being new, he introduces me to the different things while we run. One day he showed me the route to river bank, which I followed that go to there with my wife.

Some interesting things happened where we were there. For the first time in my life, I’ve seen a gay couple there and they were kissing each other. While we were there, my brother called me from Australia and he also told us an interesting fact about Hudson River that I wasn’t aware of earlier. Few years back a plane had to make emergency landing on the river after it’s engines blew. If you want to know more, you can see on wiki. Also this animation shows what happened that time.

Being a sunny day, which were rare in February 2014, we enjoyed the evening very much. Unfortunately, I didn’t take my camera with me on that day. So I’ve used my iPhone 4 to take some pictures.

to be continued ….

A new journey begins

Another big change in life is taking place. I’ve landed New York airport (JFK) a few hours ago to start my new life in the USA. After receiving my immigration visa at January 2014; I flew on February 8, 2014 leaving my crying parents along with brothers, sisters, nephews, niches, friends.

The upside (whether only or among many) of this migration is that I never knew that I’m loved by so many people. I wish I can respect all the love and care I’ve got so far and I wish I can settle myself (along with my wife) here in spite of being extremely home-seek.

Lessons learned while working with Backbone.js

I was developing a quite big Backbone.js application with my team of 2 more members. We were working on this project for about 7 months. We’ve learned an awful number of things in this journey as it was our biggest Javascript project for everyone in our team. Among many other things, OOP in Javascript always confuses me though I understand a few things better than earlier. I’ve tried to write a few things I’ve learned while working in this project; however, everything does not directly related to backbone.js

Source Code is the best documentation

I have relied on the backbonejs.org for several months for documentation purpose. However, I’ve found not everything was documented properly in the website. For example, from the website I knew fetch/sync accepts success and error as property of the options hash. What I didn’t know until I read the source code is that it also triggers sync and error events on success and failure respectively. Reading the official doc, I thought it’s possible only for save() method.

Simplified Object Copying

If I need to copy a variable/object attribute, I first need to check it whether it exists or not. Look at this example:

if(this.someAttribute){
  var localAttribute = this.someAttribute;
} else {
  var localAttribute = this.someAttribute = {} //or any default value;
}

However, while reading Backbone.js source code, I’ve learned we could write this in a very simplified one line.

var localAttribute = this.someAttribute || (this.someAttribute = {});

Changing in referenced object does not trigger events

When you change an attribute of a backbone model, change and change:attribute  events are triggered. For example,

object.set(‘name’, ‘The HungryCoder’) will trigger change and change:name events on object.  The following will not work.

var info = model.get('userInfo'); //returns a hash
info['id'] = 101;
model.set('userInfo', info);

The above change won’t trigger a change event. Here info variable is a reference to model’s userInfo and userInfo attribute in the object is already updated when you set info[‘id’] = 101;

In such cases, if you want to trigger the change events, you need to clone the attribute at first place when you are copying them.

var info = _.clone(model.get('userInfo'));
info['id'] = 101;
model.set('userInfo', info);

This will trigger change and change:info events correctly.

Learn fighting Zombies

If you’re working with Backbone.js for a while, chances are high that you’re already facing this kind of problems. Sometimes, you will notice that a particular action is triggering more than once though it is supposed to perform only once.

This happens because, even though, you remove elements from your DOM, they are still alive in your computer’s memory. Consider the example:

 

var Views.MyView = Backbone.View.extend({
  initialize: function() {
    this.model.on('change', this.render, this);
  },
  render: function() {
    //render template
    alert('hello');
  }
});

You’ve taken instance of this view and added to your DOM. When you wanted to remove these elements from DOM, you’ve called remove() method on this instance. Though the elements are removed from DOM, they are still in memory and can’t be cleaned up by Javascript’s garbage collectors as this object is still referenced from your model. It is due to the following line that you’ve written in our earlier view.

this.model.on('change', this.render, this);

The model has still a reference to this view and a referenced object is not cleaned. So your view is still going to alert you even if they are not visible in the DOM. This has been addressed in Backbone.js 0.9.9 where listenTo (and stopListening) is introduced. So you re-write the above line as following:

this.listenTo(this.model, 'change', this.render);

This will internally keep track of the bounded events and will reliably unbind any events when you call remove() on this view object.

to be updated…

Patriotism in TV Commercials

I’m big fan of TV commercials in indian televisions those try to promote patriotism. They nicely talks about their country and to love her even when advertising their products.

Though many of the TV programs (like Reality Shows, family breaking serials) ideas are borrowed from indian televisions, I was always thinking why we don’t see such patriotism in our ads?  Why our commercials do not talk to love our country, to use our local products! I think my days of frustration are over. Recently I’ve seen two tv commercials that are talking about the love for the country and make some change. I’ve embedded those two in this post.

Robi (Mobile operator) TV Commercial:

Frutika (mango juice) TV Commercial

These two are ads I watch in full each time they are broadcasted. Each time I see them I see like I’m seeing it for the first time.

If these ads can change a single person, or at least make him to think different; that’s a big success. I wish to more like these in coming days.

Handlebars helpers

In an application we are using Handlebars templating. However, we needed many custom helpers to do what we wanted to achieve. Here are some of those helpers. It may help someone who is looking for achieving similar things. Examples are included.

Adding/Subtracting

Character limit with trailing characters (optional).

Just received amazonkindle!

Today I came to office a bit late. Immediately after coming I was informed that a parcel has arrived on my name. I was expecting a dummy camera lens as it is supposed to come. However, seeing the packet I was a bit suspicious. The dummy lens’s package would not be so small. After I opened it, I could not believe my eyes. It is amazonkindle! Yes, I ordered it on 15th May from www.aliexpress.com! But still unbelievable. Do you know why? Keep following.

In aliexpress, when a order is placed and payment is done the order status was ‘Shipment Required‘. The seller was supposed to ship it and mark it as ‘Shipped’ and provide me the tracking ID. However, till now I did not receive any tracking and the order status was ‘Shipment Required’ last night. Seeing the seller is delaying unnecessarily, I canceled the order and aliexpress.com refunded me the whole money within few minutes. I also gave negative feedback to the buyer for wasting my time.

So, I guess you now can understand why I am so surprised seeing it. The seller must be stupid! Why s/he did not update the status of the order?

Anyway, as still in office, I could not get much time to explore it. I will explore it at home. I wish the seller will contact me and I will arrange a way to pay him.

The benefit of aliexpress is that it does keeps the money in escrow until you confirm that the product is reached to you and it is upto your expectation. I first heard about aliexpress.com from a member of Projanmo Forum.

My version is Kindle 3 WiFi + 3G. Costs (including shipping) was US$191. Also I had to pay 1050 tk here as excise duty and other fees.

Is it right time to buy Apple’s product from Bangladesh?

It has been about 11 months that I’ve purchased Macbook Pro 13.3 inches. Though I am extremely happy with hardware design, I am that level of unhappy due to instability of the Mac OS. I can’t run it for more than 3 days as it either hangs or become too unstable to use! Many applications including Firefox 4 crashing frequently on it.

Again, in the first month of purchase, a silica ball as been penetrated into its sound port (3.5mm) and to date it is safely there. Why? Because Aloha iShoppe, from where I’ve purchased it, said they can’t open it as it will void the Apple’s warranty though they are authorized dealer of Apple’s product! If I need to claim warranty, they would send the laptop to Singapore and it will take about 2 months to get back the laptop. Can you imagine?

Moreover from last week, power adapter for my macbook pro is dead. This morning I went to Executive Machines for asking the price of a macbook pro adapter. They said it is 8500 BDT. And they also said you can get yours one replaced from where you’ve purchased it as it has one year warranty (they also provide same warranty for their power adapters too)! Then I called to Aloha iShoppe and here is pattern of conversation:

Me: What is the warranty duration for power adapter of macbook pro?
Aloha: There is no warranty for the power adapter.
Me: But so far I know, it also has same warranty as the main body!
Aloha: When you’ve purchased it?
Me: Last june!
Aloha: Actually, it does not has so long warranty, it has about 90 days of warranty?
Me: But Executive Machines is giving 1 year warranty for power adapter.
Aloha: ummm, it is (1 year warranty) given for the products from this year, not for earlier products (power adapter)!
Me: What is the price of power adapter at your house?
Aloha: It is 9500 BDT.
Me: OMG! It is 8500 BDT at Executive Machines. Why you are charging higher prices with less warranty period?
Aloha: They might not have the product, they sometimes, tell prices for products even they don’t have.
Me: Well, they showed me the adapter

(I hang up the phone!)

If you read the above conversation, you will notice how inconsistent their information are!

With my bad experiences with Apple products, I don’t think we should buy Apple’s product unless there is a service center of Apple in Bangladesh! However, if you need to buy, I think it will be wise not to buy from Aloha iShoppe.

Few months ago, I purchased a remote control from Executive Machines by BDT 1700 whose price was asked 2800 at Aloha! So you see how much higher their prices and most importantly, poor after sales service.