在这个Angular js应用中,控制器属性没有显示在视图中

Controller property not being show in view in this Angular js app

本文关键字:属性 显示 视图 控制器 Angular js 应用      更新时间:2023-09-26

下面是我的AngularJS应用程序的aap.js

var app = angular.module('gallery',[]);
(function(){
    app.controller('GalleryController',function(){
        this.tab = true;
    }); 
})();

and gallery.html =

<html ng-app="gallery">
<head>    
    <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
    <script type="text/javascript" src="angular.js"></script>
    <script type="text/javascript" src="app.js"></script>
    <link rel="shortcut icon" href="">    
</head>
<body ng-contoller="GalleryController as g">
 <section >
 <ul>
     <li><img ng-click="tab=1" src="images/gem-01.jpg" height="100" /></li>
 </ul>
     <h1>{{g.tab}}</h1>
</section>
</body>
</html>

g.tab是控制器的属性,没有显示在视图中。为什么会这样呢?

再次编辑:我错过了你的问题。您正在使用this关键字正确,但是当您单击图像时,tab属性未显示,因为ng-click使用tab而不是g.tab。参见更新更新更新提琴:http://jsfiddle.net/z8uby8oz/2/

您不能在控制器中像这样使用this关键字。控制器方法的上下文不是你的作用域。可以看到编辑

你可以在服务中使用这种语法,但不能在控制器中使用,相反,你的作用域是与其他服务、工厂等一起注入的。

应该是

app.controller('GalleryController',function($scope){
    $scope.tab = true;
}); 

最可能是过度使用,但无论如何都添加了演示:http://jsfiddle.net/z8uby8oz/

编辑:这可以使用this关键字来实现。我不知道这一点,每天学习新的东西。这是通过在ng-controller中使用as运算符实现的。

参见更新的小提琴:http://jsfiddle.net/z8uby8oz/1/和文档我发现它在:https://docs.angularjs.org/api/ng/directive/ngController#example

我的理解是as运算符将您的作用域绑定到视图中的属性,您通过test as myScope意味着将test控制器的this关键字绑定到视图中的myScope属性。

希望你明白。

将所有值绑定到$scope

var app = angular.module('gallery',[]);
    (function(){
        app.controller('GalleryController',function($scope){
            $scope.tab = true;
        }); 
    })();

你的HTML看起来像

<html ng-app="gallery">
<head>    
    <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
    <script type="text/javascript" src="angular.js"></script>
    <script type="text/javascript" src="app.js"></script>
    <link rel="shortcut icon" href="">    
</head>
<body ng-contoller="GalleryController">
 <section >
 <ul>
     <li><img ng-click="tab=1" src="images/gem-01.jpg" height="100" /></li>
 </ul>
     <h1>{{tab}}</h1>
</section>
</body>
</html>