Angular JS:如何将未知值传递给Controller中的第三方脚本

时间:2014-09-12 18:17:19

标签: json angularjs scope single-page-application

所以我有一个项目要求我与评论服务进行第三方集成。在控制器中,我使用的工厂获取文章的JSON提要。我将第三方JavaScript代码作为控制器的init()函数的一部分,因此当每个故事详细信息视图加载时,评论部分将刷新该故事。我通过重用index.html页面使用路由和视图。因此,有一个模板被称为文章详细信息。该模板依赖于我在下面显示代码的控制器。

第三方代码要求为每个故事提供唯一ID,作为“params”选项的一部分。我使用$ routeParams.itemId来提供唯一ID +一个自定义字符串来识别该部分并避免为另一个故事复制相同的ID(因为我们有3个提要),因此文章的“Art”,视频的“Vid”我真正想要传递给这个唯一id选项的是我的JSON提要中存在的值,即PostID。

因此,JSON将是要查看的当前文章的stories.articles.postId。有没有办法在这个阶段提供JSON值?我们需要使用PostID,因为我们需要维护网站中的注释,并且此角度应用程序中的注释对于每篇文章都是同步的,而PostID是一个可以唯一标识它们并在两个环境之间共享的字段。 Controller代码如下:

(function() {

 var DetailsController = function($scope, $http, $routeParams, $sce, dataFactory) {
 storyId = $routeParams.itemId;
 uniqueId = "Art" + $routeParams.itemId;
 nextItem = $routeParams.itemId++;
 $scope.stories = [];

function init() {
  dataFactory.getStories().success(function(stories) {
    $scope.stories = stories.articles;
    $scope.whichItem = storyId; 
    $scope.nextArticle  = nextItem;
    $scope.totalList = stories.articles.length;

      $scope.SkipValidation = function(value) {
          return $sce.trustAsHtml(value);
        };    
  })
  .error(function(data, status, headers, config) {
      $log.log(data.error + ' ' + status);
  });

  $scope.todaysDate = new Date();   

  var params ={
    categoryID: 'Articles',
    streamID: uniqueId,
    version: 2,
    containerID: 'commentsDiv',
    cid:''
  }
  gigya.comments.showCommentsUI(params);
}
 init();

 };

 DetailsController.$inject = ['$scope', '$http', '$routeParams', '$sce', 'dataFactory'];

 angular.module('myApp')
   .controller('DetailsController', DetailsController);

  }());

所以基于Joao在下面提供的答案,现在我有一个指令,略微修改以使用这样的路径参数:

angular.module('myApp').directive('comments', ['$routeParams','dataFactory', function ($routeParams, dataFactory) {
    var linker = function (scope, element, attrs) {
        storyId = $routeParams.itemId;
        whichItem = storyId;
            var params = {
             categoryID: 'Articles',
             streamID: scope.uniqueId,
             version: 2,
             containerID: '=',
             cid:''
           }
        gigya.comments.showCommentsUI(params);
        };
     return {
       restrict: "E",
       replace: true,
       link: linker,
       template: '<div id="commentsDiv"></div>',
       scope: {
         uniqueId: '='
       }
    };

 }]);

它仍然没有用,但我很接近。 HTML模板需要引用我循环访问的数据集中的当前文章(25篇文章的JSON数据),所以看起来像这样:

<comments unique-id="stories[whichItem].postId"></comments>

然而,这无法评估实际值。我认为它几乎可以工作,但我最终得到的一篇文章的路由参数为-1,这没有任何意义。

也许这是不可能的......

2 个答案:

答案 0 :(得分:0)

如果这不起作用,请向我道歉,因为我对Angular很新。

首先在你的控制器上,我认为你应该这样做:

var DetailsController = function($scope, $http, $routeParams, $sce, dataFactory) {
 var storyId = $routeParams.itemId;
 var nextItem = $routeParams.itemId++;
 $scope.stories = [];

 dataFactory.getStories().success(function(stories) {
    $scope.stories = stories.articles;
    $scope.whichItem = storyId; 
    $scope.nextArticle  = nextItem;
    $scope.totalList = stories.articles.length;

    $scope.SkipValidation = function(value) {
        return $sce.trustAsHtml(value);
      };    
    })
    .error(function(data, status, headers, config) {
        $log.log(data.error + ' ' + status);
    });
}

然后我会创建一个包含插件的指令。您希望控制器与视图完全独立,以使它们更简单,更容易测试。

var comments = function(){
 return {
   restrict: "E",
   replace: true,
   template: '<div id="commentsDiv"></div>',
   scope: {
     uniqueId: '='
   }
   link: function(scope) {
      var params ={
        categoryID: 'Articles',
        streamID: scope.uniqueId,
        version: 2,
        containerID: 'commentsDiv',
        cid:''
      }
      gigya.comments.showCommentsUI(params);
   }
}

最后,在您的HTML上,要包含您的插件,只需调用指令:

<comments unique-id="stories.articles.postId"></comments>

答案 1 :(得分:0)

所以这是最终的解决方案。感谢大家的反馈。

详情控制器:

(function() {

  var DetailsController = function($scope, $http, $routeParams, $sce, dataFactory) {
  storyId = $routeParams.itemId;
  nextItem = $routeParams.itemId++;
  $scope.stories = [];

    function init() {
      dataFactory.getStories().success(function(stories) {
        $scope.stories = stories.articles;
        $scope.whichItem = storyId;
        $scope.$emit('gigya', $scope.stories[storyId].PostID);
        $scope.nextArticle  = nextItem;
        $scope.totalList = stories.articles.length;

          $scope.SkipValidation = function(value) {
              return $sce.trustAsHtml(value);
            };    
      })
      .error(function(data, status, headers, config) {
          $log.log(data.error + ' ' + status);
      });

      $scope.todaysDate = new Date();  
    }
     init();

  };

  DetailsController.$inject = ['$scope', '$http', '$routeParams', '$sce', 'dataFactory'];

  angular.module('myApp')
    .controller('DetailsController', DetailsController);

}());

指令:

angular.module('myApp').directive('gigyaComments', function () {
    return{
    template:"<div id='commentsDiv'></div>",
    link:function(scope,elem,attrs){
        scope.$on('gigya', function(event, data) {
            var params = {
                categoryID: 'Articles',
                streamID: data,
                version: 2,
                containerID: 'commentsDiv',
                cid:'',
                enabledShareProviders: '',
                useHiResIcons: true,
                showLoginBar: true,
                enabledProviders: "facebook,twitter,google"
            };
            gigya.comments.showCommentsUI(params);
        });
    }
  }

});

部分详细信息页面:

    <section ng-model="articles" class="story-details" id="main">
    <div class="article-nav"><a class="prev-article" href="#/details/{{stories.indexOf(stories[nextArticle-1])}}" ng-disabled="whichItem == 0">Previous Story</a> <a href="#/details/{{stories.indexOf(stories[nextArticle+1])}}" class="next-article"  ng-disabled="stories[nextArticle+1] == undefined">Next Story</a></div>


    <article id="main-article" data-post-id="{{stories[whichItem].PostID}}">
      <h2>{{stories[whichItem].title}}</h2>
      <div class="date">Posted on {{stories[whichItem].pubDate  | date:"MMMM d',' yyyy '@' h:mm a" }}</div>
      <div class="sharing-widget">
      <a class="facebook_custom" href="https://www.facebook.com/sharer/sharer.php?u={{stories[whichItem].link}}"></a>
      <a class="twitter_custom" href="https://twitter.com/home?status=Via: @radar_online: {{stories[whichItem].title}}: {{stories[whichItem].link}}"></a>
      <a class="plusone_custom" href="https://plus.google.com/share?url={{stories[whichItem].link}}"></a>
      <a class="pinterest_custom" href="https://pinterest.com/pin/create/button/?url={{stories[whichItem].link}}&media={{stories[whichItem].featuredImage}}&description={{stories[whichItem].title}}"></a>
      <!-- <a class="tumblr_custom" href="http://www.tumblr.com/share/link?url={{stories[whichItem].link}}"></a> -->
      <a class="email_custom" href="mailto:?&subject=I wanted you to see this article.&body=Check out this article: {{stories[whichItem].title}} {{stories[whichItem].link}}." title="Share by Email"></a>
      </div>
          <img  height="169" width="300" class="lead" ng-src="{{stories[whichItem].featuredImage}}">
        <span ng-bind-html="SkipValidation(stories[whichItem].description)"></span>
      <div class="author"><img ng-src="{{stories[whichItem].authorPhoto}}"> <span>By {{stories[whichItem].byline}}</span></div>
    </article>
    <div class="article-nav"><a class="prev-article" href="#/details/{{stories.indexOf(stories[nextArticle-1])}}" ng-disabled="whichItem == 0">Previous Story</a> <a href="#/details/{{stories.indexOf(stories[nextArticle+1])}}" class="next-article"  ng-disabled="stories[nextArticle+1] == undefined">Next Story</a></div>
    <div gigya-comments="{{stories[whichItem].PostID}}" ></div>
</section>