0

What I want to do is to create an element directive, that can have bindable attributes and can work with static values.

Ex. I have a directive myTag which should support enablel/disable of some features... I want this to work like

<my-tag enable_f1="true" enable_f2="true" />

or like

<my-tag enable_f1="{{mc.someVal1}}" enable_f2="{{mc.someVal2}}" />

Now how can I write link method, to support binding to the attributes as well as static values?

 angular.module('TestModule',[])
  .directive('myTag',function() {
      return {
          restrict: 'E',
          templateUrl: '<div></div>',
          link: function (scope, element, attrs){
                 //I can get attrs.enable_f1, attrs.enable_f2, but what if it is bound to model? 
          }
      }
  });

1 Answer 1

2

You can have an isolated scope that gets these values:

HTML:

<my-tag enable-f1="mc.someVal1" enable-f2="mc.someVal2"></my-tag>
<my-tag enable-f1="true" enable-f2="false"></my-tag>

Directive:

myApp.directive('myTag',function() {
      return {
          restrict: 'E',
          template: '<div></div>',
          scope: {
              enableF1: '=',
              enableF2: '='
          },
          link: function (scope, element, attrs){
                 console.log(scope.enableF1);
                 console.log(scope.enableF2);
          }
      }
  });

Fiddle

Sign up to request clarification or add additional context in comments.

4 Comments

hope I will use to this scopes some day :) thanks a lot, I will try
How can I get changes of enableF1, and enableF2? should I use watch? for example when it is bound, and it have been changed on model, how can I get notification in directive? if I use watch, will it be ok if the value is static?
Oh, I see it work with watch, thanks a lot for answer jsfiddle.net/db64ttxp
@ArsenMkrtchyan Yes the value of $scope.enableF1 will automatically change, good luck!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.