如何在angularjs中编写指令

Jai*_*tus 10 angularjs angularjs-directive

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

<shout-list></shout-list>
Run Code Online (Sandbox Code Playgroud)

喊名单的模板就是这样的

<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> 
Run Code Online (Sandbox Code Playgroud)

Jos*_*ler 16

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

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
      };
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

和模板文件:

<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> 
Run Code Online (Sandbox Code Playgroud)

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

控制器:

.controller( 'MainCtrl', function ( $scope ) {
  $scope.myShouts = // ...
});
Run Code Online (Sandbox Code Playgroud)

视图:

<shout-list shouts="myShouts"></shout-list>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • @Jaison,如果不是很明显:当你在Josh所示的指令中定义控制器时,那么,在HTML中使用指令的每个地方,都会创建一个控制器,它会自动与指令的范围相关联.几乎就像在使用指令的地方添加了"ng-controller"一样. (5认同)