此Angular js应用程序中未显示控制器属性

时间:2015-09-21 10:06:23

标签: javascript html angularjs

以下是我的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是控制器的属性,未在视图中显示。为什么会这样?

2 个答案:

答案 0 :(得分:3)

再次编辑:我想念您的问题。您正在使用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关键字来实现。我不知道每天都会学到新东西。即使用as中的ng-controller运算符。

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

我的理解是as运算符将您的范围绑定到视图中您传递的属性test as myScope意味着绑定this控制器的test关键字{您视图中的{1}}属性。

希望这是有道理的。

答案 1 :(得分:0)

将所有值绑定到$ 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>