【问题标题】:How to get <script> to share data to Angular Controller?如何让 <script> 将数据共享给 Angular 控制器?
【发布时间】:2016-01-14 23:37:40
【问题描述】:

我将 ASP.NET(aspx Web 表单)与 C# 和 AngularJS 一起使用。我的 index.html 文件中有一些脚本:

<script>
    function get_stuff(){
       var stuff = document.getElementById("stuff_here").value;
       console.log(stuff);
       // output: [{"name":"toy duck", "color":"yellow"},{"name":"flute", "color":"white"}]
    }
</script>
<input type='hidden' id='stuff_here' value='...' />
<button onclick="get_stuff()">RUN</button>

输出符合要求。但是,我希望能够访问我的 Angular 控制器的输出,例如在按钮上使用 ng-click 并让 Angular 函数执行相同的操作。不幸的是,按下按钮时 ng-click 不起作用。我也尝试将 var 的东西作为函数外部的全局变量,但我的 Angular 函数也无法获取它。

我怎样才能得到对象?提前感谢您的帮助!

【问题讨论】:

    标签: javascript c# asp.net angularjs webforms


    【解决方案1】:

    您可以将引导的应用程序数据保存为 Angular 服务,或者更准确地说,是 Angular 提供者。

    <script>
        var stuff = document.getElementById("stuff_here").value;
        angular.module("myApp").value("myProviderStuff", stuff);
    </script>
    

    然后在你的 Angular 应用中,

    var module = angular.module("myApp");
    module.controller("SomeController", function($scope, myProviderStuff) {
    $scope.stuff = myProviderStuff;
    

    【讨论】:

    • 哇,太棒了!我记得看过,但完全忘记了哈哈。非常感谢! :)
    • Angular 可能无法拾取模块,因此如果发生这种情况,请将 angular.module("myApp").value("myProviderStuff", stuff); jQuery $(document).ready(); 里面
    猜你喜欢
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 2013-08-14
    相关资源
    最近更新 更多