Angularjs set default content within textarea
我想大声告诉你
我想大声告诉你 2017-05-15 16:51:35
0
2
671

I have a rather strange request. . That is, when the textarea is not selected by the mouse, there will be a line of gray prompts in the text box. This is very simple, it can be achieved by using value, placeholder and so on. But when you click to select the textarea, that is, when you start typing content, there must be a line of content filled in by default in the textarea. .
There is no picture, so I will explain it using the format.

[#我是defaulttitle# I am placeholder]-->The content displayed before the textarea is not selected.
[#我是defaulttitle#]--> After selecting the textarea, the content in the text box will disappear but the default title will remain.

How to implement such a function?

我想大声告诉你
我想大声告诉你

reply all(2)
迷茫
#html
<p ng-controller="DemoCtrl">
    <textarea
            ng-model="content"
            placeholder="{{placeholder}}"
            ng-focus="focus()"
            ng-blur="blur()"></textarea>
</p>

#js
angular.module('app', [])

        .controller('DemoCtrl', function ($scope) {
            var defaultTitle = '#我是默认标题#';
            var defaultPlaceholder = '我是placeholder';
            $scope.placeholder = defaultTitle + ' ' + defaultPlaceholder;

            $scope.content = '';

            $scope.focus = function () {
                if (!$scope.content) {
                    $scope.content = defaultTitle;
                }
            };

            $scope.blur = function () {
                if ($scope.content === defaultTitle) {
                    $scope.content = '';
                }
            };
        })
淡淡烟草味

I think it’s better to turn your question into a command. Here is my basic implementation.

html

<p ng-controller="main"> <textarea my-textarea="#我是默认标题#" placeholder="我是placeholder" ng-model="myText" ng-change="log()"></textarea> </p> <script type="text/javascript"> var app = angular.module('app', []); app.directive('myTextarea', function() { return { require: 'ngModel', link: function(scope, ele, attrs, modelController) { var text = attrs.myTextarea; var placeholder = attrs.placeholder; var alltext = text + ' ' + placeholder; ele.attr('placeholder', alltext); ele.on('focus', function() { if (!modelController.$modelValue) { setVal(text); } }); ele.on('blur', function() { if (modelController.$modelValue === text) { setVal(''); } }); function setVal(v) { modelController.$setViewValue(v); modelController.$render(); } } } }); app.controller('main', ['$scope', function($scope){ $scope.log = function() { console.log($scope.myText) } }]);

The basic idea is to control it through the model's controller.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template