使用AngularJS创建自定义属性

使用AngularJS创建自定义属性

本文介绍了使用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属性值来获取属性值.第二个传递属性值并附加到指令的隔离范围.请注意,我已用链接功能替换了您的控制器.建议您阅读本文: https://docs.angularjs.org/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: https://docs.angularjs.org/guide/directive

Codepen: http://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 examplecombining the above example and the ability to change the background colour of the element which the directive attribute resides is below:

Codepen: http://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创建自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 19:50