如何在Angularjs的其他文件中使用控制器 [英] How to use a controller in an other file in Angularjs

查看:42
本文介绍了如何在Angularjs的其他文件中使用控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我过去经常用Java编写代码,其中包含许多带有对象范例的文件和带有包的MVC模式.

I'm used to code with Java with many files with object paradigm and MVC pattern with packages.

我从AngularJS开始,我试图启用一个简单的index.html,该人在javascript文件中使用控制器但不起作用.

And I begin with AngularJS, I'm trying to enable a simple index.html who use a controller in javascript file but doesn't work.

我的html文件:index.html

my html file : index.html

<html ng-app="carre">
<head>
    <script src="js/angular.js"></script>
    <script src="js/CalculCtrl.js"></script>
    <script>
        var ctrl = angular.module('carre',[]); 
    </script>
</head>
<body ng-controller="CalculCtrl">
    <div>{{2+2}}</div>
    <p>{{temps}}</p>
</body></html>

我作为控制器的javascript文件位于js/CalculCtrl.js

My javascript file as controller located at js/CalculCtrl.js

carre.controller('CalculCtrl', function($scope)
        {
             $scope.temps = 'pluie';
            }
 )

请问这是怎么了?预先感谢.

What's wrong here please ? Thanks in advance.

推荐答案

您应该反转文件包含和模块声明:

You should invert the file inclusion and the module declaration:

<html ng-app="carre">
<head>
    <script src="js/angular.js"></script>
    <script>
        var carre = angular.module('carre',[]); 
    </script>
    <script src="js/CalculCtrl.js"></script>

</head>

此外,由于在 CalculCtrl.js 中使用了名为 carre 的变量,因此您应从 ctrl 重命名在创建模块时分配的变量.代码>转换为<代码> :

Also, because you are using a variable called carre inside CalculCtrl.js, you should rename the variabile assignd when creating the module, from ctrl to carre:

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

这篇关于如何在Angularjs的其他文件中使用控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆