Armin_Fisher Armin_Fisher - 6 months ago 33
AngularJS Question

Get ng-model from a input inside directive and put it in an attribute of directive

I have "nibTextbox" directive with an input inside it,input has a ng-model,I want that ng-model value always available in "value" attribute of directive.(I don't wanna use replace)

angular.module('nib', [])
.directive('nibTextbox', function () {
return {
restrict: 'E',
scope: {
id: '@',
title: '@',
},
compile: function (element, attributes) {

var linkFunction = function (scope, element, attributes) {

}
return linkFunction;
},
controller: ['$scope', '$http', function ($scope, $http) {

}],
template: '<div value="{{nibTextBoxValue}}"><img src="" alt=""/><label>{{title}}</label><input id="{{id}}_txt" type="text" ng-model="nibTextBoxValue"></input></div>'
};
});


<nib-textbox id="ngArmin1" title="ngArmin1Title" value="{{nibTextBoxValue}}"></nib-textbox>

Answer

value is not valid for a <div> element. So let's change it to data-div. This is how it will look more or less (I usually work with typescript but I'll use plain javascript to pass the idea):

 angular.module('nib', [])
    .directive('nibTextbox', function () {
        return {
            restrict: 'E',
            scope: {
                id: '@',
                title: '@',
            },
            compile: function (element, attributes) {

                var linkFunction = function (scope, element, attributes) {

                }
                return linkFunction;
            },
             // Injected $element for manipulating attributes                
             controller: ['$scope', '$http', '$element', function ($scope, $http, $element) {


              $scope.$watch("nibTextBoxValue", function(newValue) {
              $element.attr("data-value", newValue);
          });
       }],
            templateUrl: 'template.html' // Extracting the template to a file
        };
    });

The directive template (template.html):

<div>
  <img src="" alt=""/><label>{{title}}</label>
  <input id="{{id}}_txt" type="text" ng-model="nibTextBoxValue"></input>
  </div>

In addition, remove the value attribute from your directive:

<nib-textbox id="ngArmin1" title="ngArmin1Title"></nib-textbox>