简体   繁体   中英

AngularJS show default html in p tag first but change with input

I have a p tag and an text input . I want to show default html (eg. [[enter text]] ) in the p tag at first (when the page load) but it will be modified when user write some text in the input box. Input tag will have a placeholder (eg. please enter here ), no default value. I have tried to use ng-model in input tag but it also made the value of input equal to the model which I don not want. At page load input tag value will be different than p tag.

Update : solved by this way https://jsfiddle.net/acmnosyf

I tried to make a example for you problem here .

I set the model for the p tag to a different model for the input .

<p>{{text}}</p>
<input ng-model="inputText" ng-change="changed(inputText)" type="text"> 

So when the input changes the changed function is called. In your controller you just have to implement the changed function like this

app.controller('MyCtrl', function($scope) {
  var text = "myText";
  $scope.text = text;

  $scope.changed = function(input) {
    $scope.text = input;

    // Resset text to default value
    if (input === "") {
      $scope.text = text;
    }
  }
});

Hope this helps.

Edit Like one of the comments say, one of the most elegant ways to set p is

<p>{{text ? text : "My text" }}</p>
<input ng-model="text" type="text"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM