当使用在angularjs工人和工厂功能 [英] When to use worker and factory function in angularjs

查看:97
本文介绍了当使用在angularjs工人和工厂功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对亚当·弗里曼从学习专业angularjs angularjs。

这是他定义的angularjs一个指令的示例

  myApp.directive(亮点功能(){
  返回功能(范围,元素,ATTRS){
    如果(scope.day == ATTRS [亮点]){
      element.css(色,红);
    }
  };
});

作家调用第一功能是工厂函数,它返回一个工人的功能。我不能够理解为什么他返回另一个功能。

当我写低于code时,code返回一个错误。
我不知道我做错了。

  myApp.directive(亮点功能(范围,元素,ATTRS){
  如果(scope.day == ATTRS [亮点]){
    返回element.css(色,红)
  }
});


解决方案

如果你看看在的角文档有关指令,你会看到,有两种方法可以定义一个指令。一种是使用该指令定义对象和另一个是仅仅返回一个postLink功能。

在你的书的示例显示了一种形式。你的功能不工作的原因是因为角调用你的函数,并期望它返回指令定义对象或postLink功能。取而代之的是功能,您根据您的if语句定义返回任何或的结果element.css(色,红)。

i am learning angularjs from Pro angularjs by adam freeman.

This is an example he defined an directive in angularjs

myApp.directive("highlight", function () {
  return function (scope, element, attrs) {
    if (scope.day == attrs["highlight"]) {
      element.css("color", "red");
    }
  };
});

the first function the writer calls is factory function and it returns a worker function. I' m not able to understand why he returns another function.

When i write the code below, the code returns an error. I don't know what i'm doing wrong.

myApp.directive("highlight", function (scope, element, attrs) {
  if (scope.day == attrs["highlight"]) {
    return element.css("color","red")
  }  
});

解决方案

If you take a look at the Angular docs about directives, you'll see that there are two ways you can define a directive. One is to use the directive definition object and the other is to just return a postLink function.

The example in your book shows the latter form. The reason your function doesn't work is because Angular calls your function and expects it to return a directive definition object or a postLink function. Instead the function you defined returns nothing or the result of element.css("color", "red") depending on your if statement.

这篇关于当使用在angularjs工人和工厂功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆