1

I am trying to have a span element show some $scope variable only if it is not null or empty.

I know i can accomplish this with only ng-model, but i don't understand they this won't work:

<span ng-show="x !== null" ng-model="x"></span>

or something similar to this.

1
  • 1
    <span ng-show="x !== null" ></span> should work. no need to use ng-model Sep 18, 2014 at 12:44

3 Answers 3

2

ng-model is for two-way binding (as @MK Safi said above), which means its for elements that both display values and allow users to change those values. Probably not a <span/>...

If you're just looking to show the value of the model in the span, use ng-bind or expression syntax - {{ x }}

This way, ng-show should work properly to add the relevant CSS styles as x changes.

E.g.:

<span ng-bind="x" ng-show="x !== null"></span>

or

<span ng-show="x !== null">{{ x }}</span>
0

ng-model is used mostly for input, textarea, and select elements. It's not used on span, div, or p elements, etc.

From Angular documentation on ngModel

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.

1
  • Generally speaking, yes, it can't work. ngModel is for establishing two-way data binding between user input and JavaScript object. In your span, where's the user input? What are you trying to establish two-way data binding with?
    – M.K. Safi
    Sep 18, 2014 at 12:45
0

Yes, as MK Safi says ng-model is only used to bind inupts to $scope variables. This should work though:

<span ng-show="x !== null">{{ x }}</span>

Just use the templating engine to display the value in $scope.x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.