使用指令创建部分

时间:2014-08-04 22:18:23

标签: angularjs angularjs-directive

我正在为我公司的不同博客编写一个Feed。每个Feed的格式都是相同的,只加载了不同的帖子,所以我很想去DRY并使用部分。

我们最初写了大约10次http请求(这是我们有多少博客)然后我得到了这个辉煌(或者可能不是那么多......)的想法,试图建立一个运行http的指令请求使用link属性,该属性将撤回特定于该Feed的数据。

所以,我希望有一个动态指令来生成动态http请求并接收动态数据集,然后我可以将其提供给一个部分。我希望/希望{{test}}根据link属性的值进行更改。

我绝对是新手。我是以错误的方式来做这件事的吗?提前谢谢!

app.directive('tabs', function(){
  return {
     restrict: "A",
     scope: false,
     link: function(scope, elem, attrs) {
        scope.test = attrs.link;
        scope.$apply;
        //dynamic $http function here               
  }
}

Plunker

2 个答案:

答案 0 :(得分:1)

取决于您的目标。它是否限制了请求的数量?或者它是否可以创建可重用的东西,以便您可以创建一个可以放下并处理任何博客的指令?这些并不是互相排斥的,但是解决一个并不一定能解决另一个问题。

这里大概是我要做的。

app.directive('blog', ['BlogService', function(BlogService) {
    return {
       restrict: 'A',
       templateUrl: '/app/views/blog.html',
       scope: {
           url: '='
       },
       controller: function($scope) {
          $scope.loadFeed = function() {
              $scope.loading = true;
              BlogService.loadFeed( $scope.url ).success( function(result) {
                  $scope.feed = result.feed;
              } ).complete( function() {
                  $scope.loading = false;
              });
          }
       },
       link: function(scope, element, attribs) {
          scope.$watch('url', function(newVal,oldVal) {
             if( newVal ) {
                scope.loadFeed( scope.url );
             }
          });
       }
}]);

模板:

<div class="feed">
    <span ng-show="loading">Loading feed. Please wait...</span>
    <ul ng-hide="loading">
        <li ng-repeat="post in feed">
           <h1>{{post.title}}</h1>
           <h2>{{post.date}}</h2>
           <p>{{post.description}}</p>
        </li>
    </ul>
</div>

服务:

app.factory( 'BlogService', [ '$http', function($http) {
   return {
      loadFeed: function(url) {
         return $http.get( url );
      },
      loadAllBlogs: function() {
         // this might be a service on your service that 
         // returns all of the blogs for each tab maybe.
         return $http.get('/service/blog/all'); 
      }
   }
}]);

现在,您可以将其转换为更大的控制器,该控制器可以了解您的各个Feed,并且可以在您的Feed上设置网址,如:

<div>
   <ul class="tabs">
      <li ng-repeat="blog in blogs" ng-click="selectBlog(blog)>blog.name</li>
   </ul>

   <!-- here is where I use the directive above -->
   <div blog url="selectedBlog.url"></div>
</div>

Plunker

答案 1 :(得分:0)

试试这个

app.directive('tabs', ['$http', function($http) {
    return {
        restrict: "A",
        scope: false,
        link: function(scope, elem, attrs) {
            $http.get(attrs.link).success(angular.noop);
    }
}]);

需要来自指令的$http服务,并在link

中使用它
相关问题