【问题标题】:Why I can not acces $scope value from MainController within index.cshtml?为什么我无法从 index.cshtml 中的主控制器访问 $scope 值?
【发布时间】:2016-05-25 14:16:18
【问题描述】:

我正在尝试创建 AngularJS、MVC ASP.Net 单页应用程序,所以 我在我的项目中创建了新文件夹,其中包含 app.js:

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

以及另一个包含 MainController.js 的文件夹:

myApp.controller("MainController",['$scope', function ($scope) {
$scope.naslov = "MP3 Manager"}]);

接下来,在 Views/Home 中,我已将其添加到我的 div 标签中

 ng-app="app" ng-controller="MainController"

最后我得到了这个:

<div class="row" ng-app="app" ng-controller="MainController">
<div class="col-md-6">
    <h2>Pjesme</h2>
    <p>{{ naslov }}</p>
    <p>
        ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
        enables a clean separation of concerns and gives you full control over markup
        for enjoyable, agile development.
    </p>
    <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
</div>
<div class="col-md-6">
    <h2>Playliste</h2>
    <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
    <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
</div>

当我运行这个应用程序时,它显示 {{ naslov }} 而不是 "MP3 Manager"

https://imgur.com/L1gmSBz

为什么会这样?

【问题讨论】:

  • 您是否查找过浏览器提示的任何错误消息?寻找开发者工具。出现这种行为的原因有很多,因为语法错误 - 不正确的导入
  • 您是否在 .cshtml 页面顶部为您的应用和控制器添加了脚本引用?
  • @Harvey 有什么想法吗? imgur.com/iDUYRvK
  • 是的,你没有在你的 html 文件中正确引用你的 app.js 文件,确保你的 &lt;script&gt; 标签直接指向你的 app.js 文件。

标签: javascript asp.net angularjs asp.net-mvc asp.net-mvc-4


【解决方案1】:

确保您引用了 Angularjs、您的应用和控制器。我通常将 Angularjs 引用和我的应用程序引用放在 Layout.cshtml 页面中,然后将控制器引用放在 .cshtml 页面中。

<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/app/app.js"></script>
<script src="~/Scripts/app/MainController.js"></script>

这三个你都需要。

【讨论】:

    【解决方案2】:

    你可以试试&lt;p ng-model="naslov "&gt;{{naslov }}&lt;p&gt;

    【讨论】:

    • 这肯定是问题的解决方案。它可能不是正确的解决方案,它可以使用一些解释,但它是一个答案。最后,“提供不需要提问者澄清的答案”......提问者可以插入这样的答案并获得所需的解决方案,所以这不需要澄清。对 n00bs 更加友好和欢迎怎么样?
    【解决方案3】:

    首先,我同意 Martin Welker 的观点。您不能在同一个元素上声明 ngApp 和 ngController。这不是好的做法。 其次检查Angular是否正确加载。您的 BundleConfig.cs 文件中可能有问题。小的错别字可能会导致这些愚蠢的错误。 运行它并检查您的浏览器控制台是否有任何错误。

    【讨论】:

    • 这可能不是一个好习惯,但你绝对可以将 ngApp 和 ngController 放在同一个元素上。我实际上从未听说过这是不好的做法。我在迷你SPA上做。完整的 SPA 应用程序我的结构不同。
    猜你喜欢
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多