javascript - How to set value of an input in AngularJS, without affecting its ngModel -


javascript:

.directive('search', [function () {     return {         restrict: 'a',         link: function (scope, element, attrs) {             attrs.$set('value', 'word...');             console.log(attrs);         }     }; }]); 

and value attribute added, not displayed. think has ngmodel attribute not allowing change value, i've seen somewhere in angularjs docs, setting value programmatically possible, can please show me way how?

html:

<input type="text" ng-model="query" ng-init="inputclass='input-inactive'" ng-class="inputclass" ng-focus="inputclass='input-active'" ng-blur="inputclass='input-inactive'" ng-change="searchmodelchange()" search /> 

edit: in end, want doing simple displaying 'search items...' before it's focused, when focused, set '', , when blured, check if value '' , set 'search items...'.

i know it's pretty simple, , got working once outside js function, feel it's not best solution involve "getelementbyid", think must possible angularjs link function, it's don't know how...

edit 2: different placeholder. there way solve this? say, if needed achieve different described in first edit?

something this?

.directive('search', [   function() {     return {       restrict: 'a',       require: 'ngmodel',       link: function(scope, element, attrs, ngmodel) {         var deftext = attrs.search;          ngmodel.$render = function(val) {           var text = (!val && val !== 0) ? deftext : val;           element.val(text);         }          element.on('focus', function() {           if (!ngmodel.$viewvalue)             element.val('');         });          element.on('blur', function() {           if (!ngmodel.$viewvalue)             element.val(deftext);         });        }     };   } ]); 

angular.module('app', []).directive('search', [    function() {      return {        restrict: 'a',        require: 'ngmodel',        link: function(scope, element, attrs, ngmodel) {          var deftext = attrs.search;            ngmodel.$render = function(val) {            var text = (!val && val !== 0) ? deftext : val;            element.val(text);          }            element.on('focus', function() {            if (!ngmodel.$viewvalue)              element.val('');          });            element.on('blur', function() {            if (!ngmodel.$viewvalue)              element.val(deftext);          });          }      };    }  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>  <div ng-app="app">    <input type="text" ng-model="query" search="word..." />{{query}}  </div>


Comments