app2.js

(function(){
    var app = angular.module("panel",[]);
    app.controller('PanelController',function(){
          this.tab = 1;

          this.setTab = function(setTab){
                this.tab = setTab;
          };


    });

})();

view 是:
<html ng-app="panel">

<head>
    <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
    <script type="text/javascript" src="angular.js"></script>
    <script type="text/javascript" src="app2.js"></script>\
    <style type="text/css">
    li{
        width:100px;
    }

    </style>
</head>

<body>

<section ng-controller="PanelController as panel">
    <ul class="nav nav-pills" >
        <li ng-class="{active:tab === 1}"><a ng-click="panel.setTab(1)" href="#">1</a></li>
        <li ng-class="{active:tab === 2}"><a ng-click="tab = 2" href="#">2</a></li>
        <li ng-class="{active:tab === 3}"><a ng-click="tab = 3" href="#">3</a></li>
        <li ng-class="{active:tab === 4}"><a ng-click="tab = 4" href="#">4</a></li>
    </ul>
    <h1>{{tab}}</h1>

    <div class="panel">
        <p ng-show="tab===1">Suppose this is Data coming from object for 1 </p>
        <p ng-show="tab===2">Suppose this is Data coming from object for 2 </p>
        <p ng-show="tab===3">Suppose this is Data coming from object for 3 </p>
        <p ng-show="tab===4">Suppose this is Data coming from object for 4 </p>

    </div>



</section>



</body>
</html>

问题在于单击 panel.set(1) 时未调用 <a>。为什么会这样? Controller 内部的属性 tab 都没有被访问。

最佳答案

panel.setTab 被调用。该问题是由模板中的 tab 变量引起的。你应该用 panel.tab 替换它们。
<section ng-controller="PanelController as panel"> 意味着

$scope.panel = new PanelController();

所以如果你想在你的 Controller 中使用变量。您应该添加 panel. 前缀,否则表示 $scope.tab

关于javascript - 为什么没有访问 Controller 内部的这个函数和属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32678933/

10-16 13:37