【问题标题】:Creating a modal directive, and binding click event on it in angular js创建一个模态指令,并在 Angular js 中绑定点击事件
【发布时间】:2013-12-03 01:20:13
【问题描述】:

我对 angularjs 完全陌生,我可能错过了很多概念。我正在尝试为我的应用程序创建一个模态指令,但有些东西让我感到困惑,那就是如何与该指令进行交互。

我正在使用 yeoman,它生成一个模态指令:

yo angular:directive modal --coffee

所以我的指令目录中有这段代码:

angular.module('myApp')
  .directive('modal', () ->
    templateUrl: 'views/partials/modal.html'
    restrict: 'E'
    link: (scope, element, attrs) ->
      console.log 'link --test'
  )

现在在我的modal.html 部分中,我插入了一个锚标记,它将处理点击并提醒我一些事情。

<div><a href="" ng-click="foo()">Click Me</a></div>

现在我应该把foo 函数放在哪里?

我尝试过这样的事情,但没有运气

angular.module('myApp')
  .directive('modal', () ->
    templateUrl: 'views/partials/modal.html'
    restrict: 'E'
    link: (scope, element, attrs) ->
      console.log 'link --test'
    controller: ($scope) ->
       $scope.foo = () ->
         console.log 'clicked that anchor'
  )

另一个问题,我做得对吗,我的意思是创建模态指令是否正确?还是指令以不同的方式使用?

【问题讨论】:

    标签: javascript jquery angularjs using-directives


    【解决方案1】:

    foo() 放置在指令控制器中效果很好。你走在正确的轨道上。指令是 Angular 中进行 DOM 操作的推荐位置 - 所以模式对话框是指令的一个很好的用例。

    确保您的 html 初始化 Angular 并使用如下指令:

    <div ng-app="myApp">
        <modal></modal>
    </div>
    

    这是一个working fiddle,使用您的代码和上面的 html(为了简单起见,我直接使用了模板)。

    【讨论】:

    • 这让我松了一口气,我做得对,我刚刚发现了这个错误,我有 foo() = () -&gt; 应该是 foo = () -&gt; 谢谢你的澄清。
    猜你喜欢
    • 2015-07-26
    • 1970-01-01
    • 2021-09-03
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多