Angular js : How to use link function to set value in directives

javascript jquery angularjs

44 просмотра

1 ответ

100 Репутация автора

I created directives for form input controls.

function textControlDir()
{
    return {
        transclude: true,
        restrict: 'E',
        scope: {
            data: '=data',
            default: '=default'
        },
        template: "<div ng-transclude></div><label>{{data._text}} </label><input ng-model='answer.PC' type='text' name='{{data._attributeName}}' id='{{data._attributeName}}' value='{{default}}' >"
        ,
        link: function (scope, element, attrs)
        {
            console.log('default');
            console.log(scope.default);
        }
    };
}

Html

                <div ng-if="que.QuestionData._fieldType === 'text'" >
                    <text-control-dir data="que.QuestionData" default="{{answers[que.QuestionData._attributeName]}}"></text-control-dir>
                </div> 

Here for input box I want to set value. that would be as per condition.

In link function of directive i am trying to write like

link: function (scope, element, attrs)
{
   if(scope.default == ''){
     scope.default = que.QuestionData._pageAttributes.defaultValue
   }
}
Автор: pandu das Источник Размещён: 19.07.2016 08:08

Ответы (1)


0 плюса

66066 Репутация автора

As you have suggested that you have a E element directive, so you can make use of attrs param of link function:

link: function (scope, element, attrs){
   if(attrs.default == ''){
     attrs.default = que.QuestionData._pageAttributes.defaultValue
   }
}

(function() {
  var app = angular.module('demoApp', []);
  app.controller('demoController', [demoController])
    .directive('textControlDir', [textControlDirective])

  function demoController() {}

  function textControlDirective() {
    return {
      restrict: 'E',
      template: "<div ng-transclude>::::textControlDirective::::</div>",
      link: function(scope, element, attrs) {
        console.log(attrs.default);
      }
    };
  }

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.1/angular.min.js"></script>

<div ng-app='demoApp' ng-controller='demoController'>
  <text-control-dir data="dataAttr" default="defaultAttr"></text-control-dir>
</div>

Автор: Jai Размещён: 19.07.2016 08:14
Вопросы из категории :
32x32