Thursday, May 5, 2016

AngularJS - numfmt Solution

Now.. Your JSON array returns your "number" values as "string" values. For example, instead of returning you 50, it returns you "5".
While using ng-model inside a text box of type "number", you'll receive a something called "numfmt" error. You can check it here on Angular JS documentation.
The idea is that, AngularJS doesn't provide you a direct solution for it, and asks you as a developer to provide your own "directive" to resolve this issue.
So, what to do.
Easily, use angular.forEach method to parse all the "string" values you're receiving and then convert their type into "number" using Number method.

It should be something like that, assuming you JSON is "result" and your number (string) value is "numStr"



angular.forEach(result, function(value, key) {
    value.numStr = Number(value.numStr);
});


On your view, use ng-init to initialize your model with the "number" typed value resulted from this process. Please do before your <input>, It's better to do.

Cheers

Thursday, April 28, 2016

AngularJS - $compile

Have you ever was obliged to push HTML code from controller with ng-directives, and you were asking yourself why in god it doesn't work.

For example, you've used Bootstrap popover and you need to attach ng-click to a popover item. You did, but it didn't work.

Easily, your HTML needed to be recompiled again to be executable by Angular, and here's why you should $compile to do that.

Simple Example:


$("#MyPopoverDiv").popover({ 
  html: 'true', 
  title: "", 
  content: function() { 
    return $compile("<ul>
      <li id='MyProfile'>
       <span class='glyphicon glyphicon-user'></span>
       Option 1
      </li>
      <li id='Preferences'>
       <span class='glyphicon glyphicon-cog'></span>
       Option 2
      </li>
      <li id='LogOut' ng-click='logout()'>
       <span class='glyphicon glyphicon-log-out'></span>
       Sign out
      </li>
    </ul>")($scope); 
  }, 
  placement:"bottom", 
  trigger:"focus click", 
  template:"" 
}); 

So, instead of just putting your popover content into "content" attribute. You need to use $compile first to make it ready to use ng-directives

content: function(){ 
return $compile(*Your HTML content*)($scope);
}
Don't forget to pass $compile as a dependency on controller initialization.

Cheers