Charan Cherry Charan Cherry - 1 year ago 101
Javascript Question

Unable to send parameters to ng-init

<input type="number" maxlength="1" max="5" min="0" placeholder="0" ng-model="rate">
<div ng-init="stars=Func(2)">
Rating: <span ng-repeat="x in stars track by $index">*</span>

In the above code I want to pass
, rate to the function Func.
ex: Func(rate);
here rate should pass from

JS Code:

var val='';
$scope.Func = function fun(n){
if(n == 0){
val = val + '';
} else {
val = val+'a';
return fun(n-1);
} return val;

Answer Source

You would need to rewrite your Func, such that it returns an array that contains the number of elements of your rate, so that your ng-repeat can use it for the displaying of stars.

It is as easy as

  $scope.Func = function(n) {
    return new Array(n);

Now, use your ng-init to initialize your rate to two:

<input type="number" maxlength="1" max="5" min="0" placeholder="0" ng-model="rate" ng-init="rate=2" >

Plnkr here

Edit: If your requirement is not to use Array aka collection, then ng-repeat is out of option. Fear not, we can return a string of stars instead.

Change your Func to this:

  $scope.getStars = function(n) {

    var stars = "";
    for (var i = 0; i < n; i++) {
      stars += "*";
    return stars;

And your rating will now just display the string:

<div >
  Rating: {{getStars(rate)}}

New Plnkr here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download