在外部js文件中使用Angular Directive

时间:2014-01-30 00:52:30

标签: coffeescript angularjs-directive

我正在使用CoffeeScript。我创建了一个指令来扭曲jquery ui datepicker控件。我希望能够在多个控制器中使用该指令,但是如果我将它添加到我使用的每个视图的每个coffeescript文件中,我只能将其工作,如下所示。

$ = jQuery

adminApp = angular.module("adminApp", [])

adminApp.controller "OrganizationCreateCtrl", ($scope) ->

    $scope.create = () ->
        $.ajax 'CreateOrganization',
            type: 'POST'
            dataType: 'json'
            data:
                organizationName: $scope.orgName

            error: (jqXHR, textStatus, errorThrown) ->
                $scope.success = ''
                $scope.isSuccess = false
                $scope.error = 'Could not generate Organization'
                $scope.isError = true
                $scope.$apply()
            success: (data, textStatus, jqXHR) ->
                if data.Success is true
                    $scope.success = 'Organization Created Succefully.  Organization ID: ' + data.Id
                    $scope.isSuccess = true
                    $scope.isError = false
                    $scope.error = ''
                    $scope.$apply()
                else
                    $scope.success = ''
                    $scope.isSuccess = false
                    $scope.error = 'Could not generate Organization'
                    $scope.isError = true
                    $scope.$apply()

adminApp.directive 'datepicker', ->

    restrict: 'A'
    require: 'ngModel',
    link: (scope, element, attrs, ngModelCtrl) ->
        $ ->
            element.datepicker
                dateFormat: "yy-mm-dd"
                onSelect: (date) ->
                    ngModelCtrl.$setViewValue date
                    scope.$apply()

我希望能够使用此指令而不将其包含在我创建的每个控制器中,但似乎无法使其工作。

我想创建一个只有指令的外部coffeescript文件,并在该coffeescript适用的视图页面上使用它,但似乎无法使其工作。

同样,这看起来应该很容易但是我已经厌倦了,尽管找到了很长的答案,但我已经累了。

最重要的是,我如何更多地将指令添加到外部coffeescript文件并在我的应用程序的任何控制器中使用它,而不必将其添加到我创建的每个控制器文件中。

1 个答案:

答案 0 :(得分:2)

angular-seed 中查看模块化的完成方式。 index.html包含单独的<script>代码:

<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="js/app.js"></script>
...
<script src="js/directives.js"></script>

每个文件都使用angular.module创建一个app子模块,例如,请参阅directives.js(我已翻译为CoffeeScript):

angular.module 'myApp.directives', []
  .directive 'appVersion', ['version', (version) ->
    return (scope, elm, attrs) ->
      elm.text version
首先包含

app.js,并声明它对每个子模块的依赖性:

# Declare app level module which depends on filters, and services
angular.module 'myApp', [
  'ngRoute',
  'myApp.filters',
  'myApp.services',
  'myApp.directives',
  'myApp.controllers'
]
相关问题