angular.js - Angularjs设置textarea内的默认内容

浏览:30日期:2023-02-05

问题描述

有个比较奇葩的需求。。就是在鼠标未选中textarea时文本框内会有一行灰色的提示语。这个很简单,用和value,placeholder什么的就能实现了。但是点击选中textarea也就是开始输入内容时,textarea内要有一行默认填入的内容。。没有图,我就用格式来解释一下。

【#我是默认标题# 我是placeholder】-->未选中textarea之前它显示的内容。【#我是默认标题# 】-->选中textarea后文本框内的内容,placeholder消失但是默认标题保留。

请问这样的功能要怎么样实现?

问题解答

回答1:

#html<p ng-controller='DemoCtrl'> <textarea ng-model='content' placeholder='{{placeholder}}' ng-focus='focus()' ng-blur='blur()'></textarea></p>#jsangular.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 = ’’;} };})回答2:

感觉你这个问题还是做成指令比较好,下面就是我的基本实现吧。

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)} }]);

基本思路就是通过model的controller来操控。

相关文章: