简体   繁体   中英

Angular.JS binding attribute in element directive

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? 
          }
      }
  });

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM