2014-10-10 137 views
0

参数我写了一个指令与angularjs和jQuery周期指令与angularjs

<div class="slideshow" cycle> 
    <img src="http://malsup.github.com/images/beach1.jpg" width="200" height="200" /> 
    <img src="http://malsup.github.com/images/beach2.jpg" width="200" height="200" /> 
    <img src="http://malsup.github.com/images/beach3.jpg" width="200" height="200" /> 
    <img src="http://malsup.github.com/images/beach4.jpg" width="200" height="200" /> 
    <img src="http://malsup.github.com/images/beach5.jpg" width="200" height="200" /> 
</div> 

var myApp = angular.module('myApp',[]); 

myApp.directive('cycle', function() { 
    return { 
     restrict: 'A', 
     link: function(scope, element, attrs) { 
      $(element).cycle({ 
       fx: 'fade', 
       timeout: 10 
      }); 
     } 
    }; 
}); 

这个指令都没有问题,但我想用一些参数,例如延长它,我需要的是这样的

<div class="slideshow" cycle='fade'> 
    <img src="http://malsup.github.com/images/beach1.jpg" width="200" height="200" /> 
    ... 
</div> 

你可以看到我设置了cycle ='fade'

cycle是指令,fade是我的指令cyc的参数ling效果

我怎么能有一个参数指令,并使用它如上?

<div class="slideshow" cycle='fade'> ////???????????? 
myApp.directive('cycle', function(effect) { ////????????????????? 
     return { 
      restrict: 'A', 
      link: function(scope, element, attrs) { 
       $(element).cycle({ 
        fx: effect , ////????????????????? 
        timeout: 10 
       }); 
      } 
     }; 
    }); 

回答

0

可以使用attrs

指令编译/链接功能之间共享对象包含归一化的DOM元素的属性。

$(element).cycle({ 
    fx: attrs.cycle, 
    timeout: 10 
}); 

完整代码

HTML

<div class="slideshow" cycle='fade'> 

脚本

var myApp = angular.module('myApp',[]); 
myApp.directive('cycle', function() { 
    return { 
     restrict: 'A', 
     link: function(scope, element, attrs) { 
      $(element).cycle({ 
       fx: attrs.cycle, 
       timeout: 10 
      }); 
     } 
    }; 
}); 

编辑:


您可以使用隔离范围的概念参数传递给自定义指令。

HTML

<div class="slideshow" cycle effect='fade' timeout='10'> 

脚本

var myApp = angular.module('myApp',[]); 
myApp.directive('cycle', function() { 
    return { 
     restrict: 'A', 
     scope: { 
      effect: '=', 
      timeout: '=', 
     }, 
     link: function(scope, element, attrs) { 
      $(element).cycle({ 
       fx: scope.effect, 
       timeout: scope.timeout 
      }); 
     } 
    }; 
}); 
+0

,如果我想有一个以上的参数的更多我怎么能写这个?例如我想设置FX效果和超时 – 2014-10-10 08:14:25

+0

你可以创建多个参数或者你可以使用范围 – Satpal 2014-10-10 08:15:58

+0

你可以更新你的想法的文章? (HTML和多个参数的脚本) – 2014-10-10 08:16:59

0
var myApp = angular.module('myApp',[]); 
myApp.directive('cycle', function() { 
    return { 
     restrict: 'A', 
     scope: { 
      options : "&cycle" 
     }, 
     link: function(scope, element, attrs) { 
      $(element).cycle({ 
       fx: scope.options.fx, 
       timeout: 10 
      }); 
     } 
    }; 
}); 
+0

如果我想有多个参数我怎么写这个?例如我想在你的控制器上设置FX效果和超时 – 2014-10-10 08:13:50

+0

,你可以说$ scope.cycleOpts = {foo:'foo',bar:'bar'...}; 现在要使用的是你的指令中的cycle =“cycleOpts” 你可以通过scope.options.foo – rynangeles 2014-10-10 08:21:30