如何将变量从Angular控制器传递给html <script> </script>?

时间:2016-03-25 18:13:33

标签: javascript angularjs linkedin

我的角度控制器中有变量,我想在变量中获取数据并在我的html中放入脚本标记,但我不知道如何执行此操作。我这样做是因为我想拍照并用分享按钮把它放到我的LinkedIn帖子中。基于文档here,如果我可以将控制器中的数据放入脚本标记中,那么它似乎非常简单。

例如:

controller.js

.controller('PostCtrl', function ($scope, $http, $stateParams) {
     $scope.test = "something";
     $scope.hope = 5
     $scope.array = [things];
}

HTML

<script>
var payload = {
  "comment": $scope.test "content": {
    "title": $scope.hope,
    "someArray": $scope.array,
    "submitted-url": window.location.href
  }
};
</script>

////////////////////////// 感谢大量的评论。以下是我在LinkedIn上更详细的尝试:

<script type="IN/Share" data-url={{webAddress}} data-counter="right">
                  $.get( "https://public-api.wordpress.com/rest/v1.1/sites", function( response ) {
                    var post = _.first(_.filter(response.posts, function(n){return n.title.replace(/ /g,"-").replace(/[:]/g, "").toLowerCase() === $stateParams.id}));
                    var post1 = _.assign(post, {category: _.first(_.keys(post.categories)), pic: _.first(_.values(post.attachments)).URL, credit: _.first(_.values(post.attachments)).caption, linkCredit: _.first(_.values(post.attachments)).alt, fullStory: post.content.replace(/<(?!\s*\/?\s*p\b)[^>]*>/gi,'')});
                    **var image = post1.pic;**
                    **var title = post1.title;**
                    **var webAddress = window.location.href;**

                    function onLinkedInLoad() {
                      IN.Event.on(IN, "auth", shareContent);
                    }

                   function onSuccess(data) {
                    console.log(data);
                   }

                   function onError(error) {
                    console.log(error);
                   }

                   function shareContent(title, image, webAddress) {

                    var payload = {                         
                      "content": {
                        "title": title,
                        "submitted-image-url": image,
                        "submitted-url": webAddress
                      }
                    };

                    IN.API.Raw("/people/~/shares?format=json")
                      .method("POST")
                      .body(JSON.stringify(payload))
                      .result(onSuccess)
                      .error(onError);
                   }
                  });

                  </script>

我仍然认为出现了问题。但是什么?我是否正确使用http,因为到目前为止我只使用Angular。

3 个答案:

答案 0 :(得分:4)

请参阅下面的代码片段,了解如何访问角度以外的角度范围:)

编辑(阅读更新后的问题)

你最好将所有LinkedIn脚本转码为角度方式,如kicken建议你:):

  1. 少spagetti代码
  2. 减少维护
  3. 有更多时间在YT上观看lol猫
  4. 如果您仍想这样做:) ==&gt;

    var app = angular.module('app', []);
    app.controller('MainCtrl', function($scope) {
      $scope.test = 'toto';
      $scope.hope = 'My Title';
      $scope.array = ['A', 'B', 'C'];
      $scope.payload = {};
    });
    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script>
        var myFunction = function() {
    
          var e = document.getElementById('app');     
          var $scope = angular.element(e).scope();
          console.log($scope.payload);
          $scope.payload = {
            "comment": $scope.test,
            "content": {
              "title": $scope.hope,
              "someArray": $scope.array,
              "submitted-url": window.location.href
             }
          };
          $scope.$apply();
        };
    </script>
    <body ng-app="app" ng-controller="MainCtrl" id="app">
      <p>Hello {{payload}}!</p>
      <button onclick="javascript:myFunction()">Click me</button>  
    </body>
    

答案 1 :(得分:1)

不是尝试将数据从Angular传递到通用<script>标记,而是需要将LinkedIn代码移动到Angular中。

快速浏览the JavascriptSDK documentation表明这是在请求中进行链接的关键代码:

IN.API.Raw("/people/~/shares?format=json")
  .method("POST")
  .body(JSON.stringify(payload))
  .result(onSuccess)
  .error(onError);

您可以做的就是将代码放在角度代码中,无论您需要它。您提到有效负载的数据来自$ http请求,因此您可能希望将其放入$ http成功处理程序中。

$http({url:'/whatever'}).then(function(response){
    var payload = { /* Generate payload */ };

    IN.API.Raw("/people/~/shares?format=json")
      .method("POST")
      .body(JSON.stringify(payload))
      .result(onSuccess)
      .error(onError);

    function onSuccess(){ /* LinkedIn success */ }
    function onError(){ /* LinkedIn error */ }
});

答案 2 :(得分:1)

正如其他人所建议的那样,如果可能的话,将所有javascript代码移动到控制器中将是最佳解决方案。为此,您的控制器看起来像这样:

.controller('PostCtrl', function ($scope, $http, $stateParams) {
  $scope.test = "something";
  $scope.hope = 5
  $scope.array = [things];


  $scope.sendData = function () {
    var data = $.param({
      "comment": $scope.test,
      "content": {
      "title": $scope.hope,
      "someArray": $scope.array,
      "submitted-url": window.location.href
    });

    var config = {
      headers : {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
      }
    }

    $http.post('https://api.linkedin.com/v1/people/~/shares?format=json', data, config)
      .success(function (data, status, headers, config) {
        //it worked
      })
      .error(function (data, status, header, config) {
        //there was an error
    });
  };    
}

然后,在你的html中,你会在你用来分享的表格上加上ng-submit =“sendData()”。如果共享内容不在表单中,则可以执行ng-click =“sendData()”。