使用AngularJS创建自定义属性

编程入门 行业动态 更新时间:2024-10-20 13:37:09
本文介绍了使用AngularJS创建自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是AngularJS的新手.我正在尝试编写一条指令,该指令将根据某些情况设置<div>的background-color.从本质上来说,我希望能够编写以下代码:

I'm new to AngularJS. I'm trying to write a directive that will set the background-color of a <div> based on some scenario. Essentially, in my view, I want to be able to write this code:

<div effect-color="#2D2F2A">content here</div>

<div effect-color="{{effectColor}}">content here</div>

我知道我需要一个指令.目前,我正在这样做:

I know I need a directive. Currently, I'm doing this:

.directive('effectColor', [ function () { return { restrict: 'A', controller: [ '$scope', '$element', '$attrs', '$location', function ($scope, $element, $attrs, $location) { // how do I get the value of effect-color here? } ] } } ]);

我不确定如何获取属性本身的值.我需要添加范围吗?我只想要属性值.

I'm not sure how to get the value of the attribute itself. Do I need to add a scope? I just want the attribute value.

谢谢!

推荐答案

这里有两种方法...第一种方法是通过查看指令的elements属性值来获取属性值.第二个传递属性值并附加到指令的隔离范围.请注意,我已用链接功能替换了您的控制器.建议您阅读本文: docs.angularjs/guide/directive

Here are two methods... First gets the attribute value through looking at the elements attribute value of your directive. The second gets passed the attribute value and attached to the isolated scope of your directive. Please note I have replaced your controller with a linking function. I suggest you give this article a read: docs.angularjs/guide/directive

Codepen: codepen.io/anon/pen/cGEex

HTML:

<div ng-app="myApp"> <div effect-color-one="#123456"></div> <div effect-color-two="#123456"></div> </div>

JavaScript:

JavaScript:

angular.module('myApp', []) .directive('effectColorOne', function () { return { restrict: 'A', link: function (scope, element, attrs) { console.log('example 1: ' + attrs.effectColorOne); } } } ) .directive('effectColorTwo', function () { return { restrict: 'A', scope: { effectColorTwo: '@' }, link:function (scope) { console.log('example 2: ' + scope.effectColorTwo); } } } );

另一个示例 结合上面的示例和更改指令属性所驻留的元素的背景颜色的功能,如下所示:

Another example combining the above example and the ability to change the background colour of the element which the directive attribute resides is below:

Codepen: codepen.io/anon/pen/HospA

HTML:

<div ng-app="myApp"> <div effect-color="red">Hello</div> </div>

JavaScript:

JavaScript:

angular.module('myApp', []) .directive('effectColor', function () { return { restrict: 'A', link: function (scope, element, attrs) { element.css('background-color', attrs.effectColor); } } } );

更多推荐

使用AngularJS创建自定义属性

本文发布于:2023-10-27 03:13:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532144.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   属性   AngularJS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!