【问题标题】:how to write a directive in angularjs如何在angularjs中编写指令
【发布时间】:2013-01-15 05:51:05
【问题描述】:

我喜欢使用指令制作自定义组件。我检查了很多教程,它让我感到困惑,任何人都可以解释指令是如何工作的。我打算制作的组件是

<shout-list></shout-list>

喊单的模板是这样的

<div class="shout" ng-repeat="shout in shouts">
    <p>{{shout.message}}</p>
    <img src="media/images/delete.png" width="32" height="32" ng-click="deleteShout({{$index}},'{{shout._id}}')"/>
</div> 

【问题讨论】:

  • egghead.io 的短视频帮助我理解指令。以及来自官方 AngularJS 博客的博文 About those directives 的视频。
  • 我看了视频,但对何时使用编译器和链接器感到困惑
  • 通俗地说:编译器用于修改模板,链接器用于将数据绑定到已编译的模板
  • @MaximPonomarev 在哪种情况下使用编译器和链接器?你能具体说明我们什么时候使用它吗..
  • 我写了一篇博客文章让人们开始编写指令:seanhess.github.io/2013/10/14/angularjs-directive-design.html

标签: angularjs angularjs-directive


【解决方案1】:

这是你的指令,带有一些内联 cmets:

angular.module( 'directives', [] ).directive( 'shoutList', function () {
  return {
    restrict: 'E', // allow as an element; the default is only an attribute
    scope: {       // create an isolate scope
      shouts: '='  // map the var in the shouts attribute to this scope
    },
    templateUrl: 'templates/shoutList.html', // load the template file
    controller: function ( $scope ) {
      // we declare a your function for use in the view
      $scope.deleteShout = function ( idx, id ) {
        // do whatever
      };
    }
  };
});

还有模板文件:

<div class="shout" ng-repeat="shout in shouts">
  <p>{{shout.message}}</p>
  <img src="media/images/delete.png" width="32" height="32" 
    ng-click="deleteShout({{$index}},'{{shout._id}}')" />
</div> 

现在您可以在代码中使用它,如下所示:

控制器:

.controller( 'MainCtrl', function ( $scope ) {
  $scope.myShouts = // ...
});

查看:

<shout-list shouts="myShouts"></shout-list>

希望这会有所帮助!

【讨论】:

  • 非常感谢。在这种情况下,我们使用编译器和链接器方法。如果可能的话,你能通过连接上面的答案来解释吗?
  • @Josh,你对 deleteShout 函数应该在哪里定义有意见吗:正如你在控制器中显示的与在链接函数中定义它:link: function(scope) { scope.deleteShout = function(...) {...} }
  • @MarkRajcok 只是一个非常弱的意见。据我了解,控制器和链接功能之间只有一些细微差别(例如 ctrls 先运行),但这些都不会影响这个示例。对我来说,为了与框架的其余部分保持一致,在控制器内部发生作用域操作功能更有意义,但这并不重要。但实际上,在这种情况下,我什至不会在指令中执行deleteShout;该指令应该专注于 DOM 的东西,应该调用一个 '&' attr 来进行实际的删除,以及关注点分离和所有......
  • @Jaison,以防不明显:当您在 Josh 显示的指令中定义控制器时,然后,在 HTML 中使用该指令的每个地方,都会创建一个控制器,并且自动与指令的范围相关联。几乎就像在使用指令的任何地方都添加了“ng-controller”。
猜你喜欢
  • 2015-01-09
  • 1970-01-01
  • 2014-07-07
  • 2015-12-07
  • 2017-05-08
  • 2016-10-14
  • 2014-04-02
  • 2013-06-09
  • 1970-01-01
相关资源
最近更新 更多