【问题标题】:Directives in AngularJSAngularJS 中的指令
【发布时间】:2015-08-03 14:49:49
【问题描述】:

您好,我正在尝试学习 AngularJS 指令,我非常接近,但想通过清理和解耦我的指令代码来扩展我的学习。

指令:

app.directive('ngSparkline', function () {
var url = "http://api.openweathermap.org/data/2.5/forecast/daily?mode=json&units=imperial&cnt=14&callback=JSON_CALLBACK&q=";
return {
    restrict: 'A',
    require: '^ngCity',
    transclude: true,
    scope: {
        ngCity: '@'
    },
    templateUrl: 'app/partials/weatherTemplate.html',
    controller: ['$scope', '$http', function($scope, $http) {
  $scope.getTemp = function(city) {}
}],
    link: function (scope, iElement, iAttrs) {
        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);
            }
        });
    }
};

});

如您所见,我不是在尝试编写内联模板,而是使用 templateUrl。现在问题出在控制器上,当我尝试使用 .js 控制器而不是内联编写控制器代码时,我收到一个错误。我如何做到这一点。

我试过了:

我试过了

controller: '@', 
name: 'ctrl'  

我将“ctrl”传递为:

<div ng-sparkline ng-city="San Francisco" ctrl="weatherController"></div>

它让我找不到控制器。我的项目结构如下所示。

  • 我做错了什么?
  • 有更好/正确的方法吗?

请提出建议。

注意:我正在从“http://www.ng-newsletter.com/posts/directives.html”学习这个练习

【问题讨论】:

  • 您的控制器是否在您的应用程序中正确引用?就像您将它包含在您的脚本引用或捆绑中一样?
  • 您实际上应该将控制器的名称直接传递给指令上的controller 属性,就像您指定templateUrl 属性的路径一样。该指令应该拥有并直接控制它的控制器。消费者必须自己为指令提供或管理控制器是不合适或有用的;控制器应该保存指令使用的所有逻辑,并且不应该依赖消费者来提供这个逻辑。
  • @Claies 我尝试传递控制器,即 'app/controllers/mycontroller.js' 并抛出错误无效函数。
  • controller 属性不采用文件路径,它采用函数 DI 注入作为参数来查找函数(即 weatherController)。 Angular 可以从磁盘上的任何位置注册函数,只要在 HTML 页面上加载了 &lt;script&gt;,您的指令就不会关心它的存储位置。但是,它确实关心 模板 的存储位置,因为它们没有对应的 &lt;script&gt;
  • 所以你的意思是把它作为 ['$weatherController', function ($weatherController) { ?? }; }],如果我错了你能纠正我吗?

标签: angularjs angularjs-directive


【解决方案1】:

为什么不在你的元素上指定ng-controller?如果WeatherController 在其他地方定义,那么它不会影响您的指令定义,只需将控制器放在外面即可。

<div ng-sparkline ng-city="San Francisco" ng-controller="WeatherController"></div>

如果您确实在某处定义了控制器

app.controller('WeatherController', ['$scope', '$http', function ($scope, $http) {
    $scope.getTemp = // …
}]);

(顺便说一句,如果你注意到的话,AngularJS 的约定是以大写的方式命名控制器。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    相关资源
    最近更新 更多