无法在控制器AngularJs之间共享数据

时间:2015-10-03 06:12:26

标签: angularjs ng-controller

嗨,我是AngularJS的新手。 这是我的index.html文件 http://clip2net.com/s/3oknPG6

<!doctype html>
<html ng-app="app">
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
        <meta charset="utf-8">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Angular route</title>
        <link rel="stylesheet" href="css/style.css">
        <link rel="author" href="humans.txt">
         <script src="angular.js"></script>
        <script src="node_modules/angular-ui-router/release/angular-ui-router.min.js"></script>
        <script src="app/app.js"></script>
        <style>
        body {
            padding: 20px;
        }
        </style>


    </head>
    <body>
    <div ng-view></div>

    <script src="js/main.js"></script>

    </body>
</html>

这是app.js文件:

angular.module("app", ["ui.router"])


.config(function config($stateProvider){
        $stateProvider.state("index", {
            url:"",
            controller: "FirstCtrl as first",
            templateUrl: "templates/first.html"
        })
    })

.controller("FirstCtrl", function FirstCtrl(){
            var first = this;
            first.greeting = "First";
        });

和first.html文件:

<input type="text" ng-model="first.greeting"/>
    <div ng-class="first.greeting">{{first.greeting}}</div>

我无法在视图中获取数据,请帮我解决这个问题。此外,我收到此错误:无法读取属性&#39; isDefined&#39;未定义的。

3 个答案:

答案 0 :(得分:0)

您在index.html中加载了两次'ui-router'依赖性。也许这就是问题?在包含angular.min.js之后加载你的ui路由器。

答案 1 :(得分:0)

我认为问题在于配置......

controller: "FirstCtrl as first"

您可以使用controllerAs字段。试试这个:

controller: "FirstCtrl"
controllerAs: "first"

这应该有希望解决围绕&#34; isDefined&#34;未定义的。 Angular实际上会寻找名为&#34; FirstCtrl作为第一个&#34;。

的控制器

希望这有帮助。

答案 2 :(得分:0)

什么是<script src="js/main.js"></script>还有  <script src="app/app.js"></script>并且你已经加载了ui-router两次,删除 <script src="node_modules/angular-ui-router/release/angular-ui-router.min.js"></script> 我也不确定你想通过编写

来查看first.html文件
ng-class="first.greeting"

ngClass指令允许您通过数据绑定表示要添加的所有类的表达式,在HTML元素上动态设置CSS类。 More Info on ng-class