简体   繁体   English

如何在指令中使用require选项

[英]How to use require option in directives

In documentation I can read next for the require option: 在文档中,我可以阅读下下require选项:

When a directive uses this option, $compile will throw an error unless the specified controller is found. 当指令使用此选项时,除非找到指定的控制器,否则$ compile将引发错误。 The ^ prefix means that this directive searches for the controller on its parents (without the ^ prefix, the directive would look for the controller on just its own element). 前缀^表示此伪指令在其父级上搜索控制器(没有^前缀,伪指令将仅在其自己的元素上查找控制器)。

So I try to use it: 所以我尝试使用它:

<div ng-sparkline></div>

app.directive('ngCity', function() {
  return {
    controller: function($scope) {}
  }
});

app.directive('ngSparkline', function() {
  return {
    restrict: 'A',
    require: '^ngCity',
    scope: {},
    template: '<div class="sparkline"><h4>Weather </h4></div>',
    link: function(scope, iElement, iAttrs) {
      // get weather details
    }
  }
});

But I have an error if my html have not ng-city attribute, so if I need controller of another directive - need to add exactly same attribute in html, but why ( <div ng-sparkline ng-city="San Francisco"></div> )? 但是,如果我的html不具有ng-city属性,则会出错,因此,如果我需要另一个指令的控制器-需要在html中添加完全相同的属性,但是为什么( <div ng-sparkline ng-city="San Francisco"></div> )? And it looks on another directive's controller with this name (directive!!!) but not at controller with this name, is that true? 并在具有该名称(指令!!!)的另一个指令的控制器上查找,但不在具有该名称的控制器上查找,是真的吗? Thanks. 谢谢。 Just want to make it clear 只是想说清楚

With require you can get the controller of another (cooperating) directive. 使用require可以获取另一个(协作)指令的控制器。 The controller in Angular is not semantically a function, but an object constructor, ie called essentially as var c = new Controller() (this is a simplification for the sake of clarity). Angular中的控制器在语义上不是函数,而是对象构造函数,即,基本上称为var c = new Controller() (为清楚起见,这是一种简化)。 Since the controller is an object, it can have properties and methods. 由于控制器是对象,因此它可以具有属性和方法。 By requiring the controller of another directive, you gain access to those properties/methods. 通过要求另一个指令的控制器,您可以访问那些属性/方法。 Modifying your example to demonstrate: 修改示例以演示:

app.directive('ngCity', function() {
    return {
        controller: function($scope) {
            this.doSomething = function() {
                ...
            };
        }
    }
});

app.directive('ngSparkline', function() {
    return {
        restrict: 'A',
        require: '^ngCity',
        scope: {},
        template: '<div class="sparkline"><h4>Weather </h4></div>',
        link: function(scope, iElement, iAttrs, ngCityController) {
            // use the controller, e.g.
            ngCityController.doSomething();
        }
    }
});

In your case, the city would be a property of the controller of the ngCity directive, exposed as a property. 在您的情况下, city将是ngCity指令的控制器的属性,并作为属性公开。 It will be read by the ngSparkline to know for which city the graph is about. ngSparkline将读取该ngSparkline以了解该图针对的城市。

<b> added directives.js</b>
<code>
app.directive('ngSparkline', function () {
    return {
        restrict: 'A',
        require: '^ngCity',
        scope: {
            ngCity: '@'
        },
        templateUrl: '/scripts/templates/tpl.html',
        controller: ['$scope', '$http', function ($scope, $http) {
            var url = "https://api.openweathermap.org/data/2.5/forecast/daily?mode=json&units=imperial&cnt=7&callback=JSON_CALLBACK&q=";
            console.log(url + $scope.ngCity);
            $scope.showTemp = function () {
                $scope.getTemp($scope.ngCity);
            };
            $scope.getTemp = function (city) {
                $http({
                    method: 'JSONP',
                    url: url + city
                }).success(function(data) {
                    var weather = [];
                    angular.forEach(data.list, function(value){
                        weather.push(value);
                    });

                $scope.weather = weather;

                });
            }
        }],
        link: function (scope, iElement, iAttrs, ctrl) {
            scope.getTemp(iAttrs.ngCity);
            scope.$watch('weather', function (newVal) {
                if (newVal) {
                    var highs = [];
                    angular.forEach(scope.weather, function (value) {
                        highs.push(value.temp.max);
                    });
                    //chartGraph(iElement, highs, iAttrs);

                }
            });
        }
    }
}).directive('ngCity', function () {
    return {
        controller: function ($scope) {
            //console.log("hello");
        }
    }
});
</code>

<b> and added tpl.htm</b>

<code>
<div class="sparkline">
    <input type="text" data-ng-model="ngCity">
    <button ng-click="showTemp()" class="btn1">Check {{ngCity}}</button>
    <div style="color:#2743EF">{{weather}} ºC</div>
    <div class="graph"></div>
</div>
</code>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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