1

Hi Im trying to create a directive to pass some value to my ng-model, in my directive i have a controller inside my directive and and i want to pass the value of it in my ng-model

Lets just say i have a string value, when i click the $scope.speakUP it should be pass it on the ng-model

.directive('speak', function(){
          return {
            restrict: 'A',
             require: 'ngModel',
            scope: true,
            template: '<i ng-click = "speakUP()" class="icon ion-mic-a larger"></i>',

            controller: function($scope, $element){
             $scope.speakUP = function(){

                     $scope.passThisString = "Sample Data";

                 }

        }

This is my HTML

  <input type="text" ng-model="sampleModel" speak>
VLR
  • 312
  • 1
  • 4
  • 18
  • Possible duplicate of [Easiest way to pass an AngularJS scope variable from directive to controller?](https://stackoverflow.com/questions/13318726/easiest-way-to-pass-an-angularjs-scope-variable-from-directive-to-controller) – Durga Jul 12 '17 at 10:13
  • I cant understand the idea behind this, but it is totally wrong. You cant use input as a container and set a template for it. – Yordan Nikolov Jul 12 '17 at 10:14
  • @YordanNikolov sorry.. but can you help me what is the alternative way? – VLR Jul 12 '17 at 10:20

1 Answers1

2

this is a quick example from where you can start implement your goals.

 app.directive('inputField', function () {
    return {
        require: '?ngModel',
        template: '<input ng-model="value" ng-change="onChange()"><i ng-click="speakUP()" class="icon ion-mic-a larger">click</i>',
        link: function ($scope, $element, $attrs, ngModel) {
            if (!ngModel) return;

            $scope.speakUP = function(){
              ngModel.$setViewValue('your data');
              ngModel.$render(); 
            }

           $scope.onChange = function() {
             ngModel.$setViewValue($scope.value);
           };

           ngModel.$render = function() {
             $scope.value = ngModel.$modelValue;
           };
        }
    };
});

HTML

<input-field name="sampleModel" ng-model="sampleModel"></input-field>
Yordan Nikolov
  • 2,598
  • 13
  • 16