2

I am currently working on a web application that uses bootstrap and angular.js, and I was running into some difficulty setting the default value of a span embedded within the HTML code of one of the pages.

Previously, I was able to use ng-model to set and modify the values of an HTML element within the HTML code from the angular controller found in a separate file. This is what the controller looks like:

angular.module('mediaPlaylistApp', [])
    .controller('mediaPlaylistCtrl', ['$scope', 'sharedProperties', .....,
        function($scope, sharedProperties, .....,){
        //many lines of code in here
}]);

Within this, I am able to set attributes of the $scope variable that can then be used by elements on the HTML page. For example, I can set a checkbox to be checked with the following JS line in the above controller:

$scope.areAllSelected = true;

When it is used in conjunction with the following HTML code:

<input type="checkbox" ng-model="areAllSelected">

This works as expected. However, my issue arises when I try to replicate this technique for a different span element.

When I insert this JS line into the angular controller:

$scope.playlistName = 'Enter Playlist Name Here';

In conjunction with this HTML code:

<span ng-model="playlistName">
</span>

It does not work as expected, as the span remains blank and not displaying the string 'Enter Playlist Name Here'. What could be causing this behavior? Does ng-model not work for elements other than input, or is it a simple mistake I've made or a completely unrelated issue? Any help on this would be appreciated.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
ajc2000
  • 651
  • 5
  • 20

2 Answers2

3

Taken from the docs:https://docs.angularjs.org/api/ng/directive/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."

Yes, you can't use ng-model with span. Instead you can use ng-bind.

<span ng-bind="playlistName"></span>

Alternative is that you can wrap the value defined on scope with interpolation operator {{}}

  <span>{{playlistName}}</span>

Why ng-bind is better than {{}} ?

Vivz
  • 6,625
  • 2
  • 17
  • 33
0

You are right. ng-models sets the value of the element while span has no inherent value. You have to display it like this:

<span>
{{playlistName}}
</span>
Jarek Kulikowski
  • 1,399
  • 8
  • 9