0

Example:

var scope = {
      thing: 'Monkey'
    };
$interpolate("Awesome{{' ' + thing}}!")(scope);
                       ^^^

I don't want to print a white space when thing is null or undefined.

Expectectations:

  1. scope.thing == 'Monkey'

    -> "Awesome Monkey!"

  2. scope.thing == null

    -> "Awesome!"

Is it possible to specify {{' ' + thing}} somehow to not print anything when thing is null or undefined?

EDIT:

Possible I need something like this {{ thing && (' ' + thing) }}, but I guess that with angular it should be possible to be done in more elegant way.

PS I'm new in Angular, so sometimes I develop a wheel :)

3 Answers 3

2

You can try to go with IIf notation:

$interpolate("Awesome{{thing ? ' ' + thing : ''}}!")(scope);
Sign up to request clarification or add additional context in comments.

Comments

2

EDIT: first time i misunderstood the question. Now it should be ok.

app.controller('MainCtrl', function($scope) {
  $scope.model = {
      thing: 'Monkey',
      emptyThing: null
  };

  $scope.print = function (value) {
      if (value)
      {
         return ' ' + value;
      }
      return '';
    };
});

  <body ng-controller="MainCtrl">
    <p>Hello{{print(model.thing)}}!</p>
    <p>Hello{{print(model.emptyThing)}}!</p>
  </body>

You can create a filter if yo want to reuse this functionality across multiple controllers:

app.filter('addWhitespace', function() {
    return function(input) {
     if (input)
      {
         return ' ' + input;
      }
      return '';
    };
});

<p>Hello{{model.thing | addWhitespace}}!</p>

http://plnkr.co/edit/J9PKfhNC1SzKZKw7Z5yl?p=preview

Tip #2: Do not replace the entire scope with your custom object create a new property on the scope instead.

1 Comment

I like the idea about print() that is used as a wrapper.
1

Great answers. It's not that much logic but you could put it into the controller. For better separation and testability.

Just create a function like this in the controller:

$scope.thingOrNothing = function(){
  return !$scope.model.thing || ' ' + $scope.model.thing + ' ';
}

And in html, call the function like this:

<body ng-controller="MainCtrl">
  <p>Hello{{thingOrNothing()}}Men!</p>
</body>

2 Comments

This is a good idea! I can use thingOrNothing() as a wrapper and send data as argument, for example Hello{{thingOrNothing(thing)}}Men!.
Yes, exactly like MajoB does it with his $scope.print function. We wrote our answers at the same time :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.