【问题标题】:Pass AngularJS variable to script tag in html view将 AngularJS 变量传递给 html 视图中的脚本标记
【发布时间】:2018-12-02 19:41:12
【问题描述】:

这就是问题所在。我有一个需要嵌入到我的 AngularJS 应用程序中的第 3 方脚本,在 html 中作为 <script> 标记。我需要将范围变量传递给这个脚本(姓名、电子邮件等)。我在这里的第一次尝试是弄清楚是否可以在页面加载时将范围变量从控制器传递给脚本标记。也许有更好的方法,比如让脚本成为模板,但我不确定。我担心如果我在这个基本概念上取得成功,脚本标签会在变量传递之前呈现真实数据。

这是 HTML:

  <body>
    <div ng-controller="MainCtrl">
        Angular variable: {{foo}}
    </div>
  </body>
  <script type="text/javascript">
    console.log(foo); // $scope.foo?
  </script>

这是控制器:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
      $scope.foo = 'bar';
})

Plunker:https://plnkr.co/edit/5rcnqUxHRHMthHmkwVuZ?p=preview

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    如果您想将第三方脚本(jQuery 插件或其他东西)嵌入到您的 AngularJS 应用程序中,您应该为此脚本编写包装器(简单的 directivecomponent

    你提出的方式行不通 - 我保证

    我找到了一个简单的example 告诉你如何创建 AngularJS 指令并包装一些简单的 jquery 插件:

    <html>
    <head>
        <title>AngularJS wrapp jquery plugin</title>
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script src="https://raw.github.com/SamWM/jQuery-Plugins/master/numeric/jquery.numeric.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
    
        <script type="text/javascript">
            var app = angular.module('myApp', []);
            app.directive('numberMask', function() {
                return {
                    restrict: 'A',
                    link: function(scope, element, attrs) {
                        $(element).numeric();
                    }
                }
            });
        </script>
    </head>
    
    <body>
        <div ng-app="myApp">
            <div>
                <input type="text" min="0" max="99" number-mask="" ng-model="message"> 
            </div>
        </div>
    
    </body>
    

    【讨论】:

    • 感谢您的回复。第三方脚本设置一些变量并从 http 调用中提取额外的 JS 代码。这会是组件或指令路由的问题吗?
    • 我认为这不会是一个问题 - 你必须尝试,在顶部你有一个小提示。祝你好运
    猜你喜欢
    • 1970-01-01
    • 2022-06-23
    • 2012-10-15
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    相关资源
    最近更新 更多