2016-08-05 37 views
1

這是我的代碼:NG-如果不與getDay()工作

<h2>HEUTE</h2> 
    <h2 ng-if="d == 1">Montag: {{cat.montag}}</h2> 
    <h2 ng-if="d == 2">Dienstag: {{cat.dienstag}}</h2> 
    <h2 ng-if="d == 3">Mittwoch: {{cat.mittwoch}}</h2> 
    <h2 ng-if="d == 4">Donnerstag: {{cat.donnerstag}}</h2> 
    <h2 ng-if="d == 5">Freitag: {{cat.freitag}}</h2> 
    <h2 ng-if="d == 6">Samstag: {{cat.samstag}}</h2> 
    <h2 ng-if="d == 0">Sonntag: {{cat.sonntag}}</h2> 

控制器:

$scope.getDate = function() { 
     var n = new Date(); 
     $scope.d = n.getDay(); 
    } 

的問題是,當我插入到第二NG-IF(Dienstag)不再顯示正確的一天。我錯過了什麼嗎?

+0

到第二NG如果?第二個ng-if在哪裏? 'd'的價值是什麼? – Weedoze

+0

它爲我工作,你有沒有忘記調用getDate的地方?你可以添加一些代碼嗎?這個唯一的代碼片段是可以使用的。 – Walfrat

+1

你忘記調用的函數'getDay()' – Weedoze

回答

1

看到這個功能,你在這裏定義:

myApp.controller("myController", ['$scope', '$http', 
    function($scope, $http) { 
    $scope.getDate = function() { 
     var n = new Date(); 
     $scope.d = n.getDay(); 
    } 
]); 

它僅僅是價值分配到$scope變量d。如果這就是你想要做的那麼爲什麼不直接通過聲明這些變量呢?像這樣

myApp.controller("myController", ['$scope', '$http', 
    function($scope, $http) { 
     var n = new Date(); 
     $scope.d = n.getDay(); 
    } 
]); 

<html ng-app="myApp"> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
</head> 
 

 
<body ng-controller="myController"> 
 

 
    <h2>HEUTE</h2> 
 
    <h2 ng-if="d == 1">Montag: {{cat.montag}}</h2> 
 
    <h2 ng-if="d == 2">Dienstag: {{cat.dienstag}}</h2> 
 
    <h2 ng-if="d == 3">Mittwoch: {{cat.mittwoch}}</h2> 
 
    <h2 ng-if="d == 4">Donnerstag: {{cat.donnerstag}}</h2> 
 
    <h2 ng-if="d == 5">Freitag: {{cat.freitag}}</h2> 
 
    <h2 ng-if="d == 6">Samstag: {{cat.samstag}}</h2> 
 
    <h2 ng-if="d == 0">Sonntag: {{cat.sonntag}}</h2> 
 

 
    <script> 
 
    var myApp = angular.module('myApp', []); 
 

 
    myApp.controller("myController", ['$scope', '$http', 
 
     function($scope, $http) { 
 
     var n = new Date(); 
 
     $scope.d = n.getDay(); 
 
     } 
 
    ]); 
 
    </script> 
 
</body> 
 
<html>

2

其工作..

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

 
app.controller('MainCtrl', function($scope) { 
 
    var n = new Date(); 
 
    console.log(n.getDay()); 
 
     $scope.d = n.getDay(); 
 
});
<script data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js" data-require="[email protected]"></script> 
 
    
 
<body ng-app="plunker" ng-controller="MainCtrl"> 
 
    <h2>HEUTE</h2> 
 
    <h2 ng-if="d == 1">Montag: {{cat.montag}}</h2> 
 
    <h2 ng-if="d == 2">Dienstag: {{cat.dienstag}}</h2> 
 
    <h2 ng-if="d == 3">Mittwoch: {{cat.mittwoch}}</h2> 
 
    <h2 ng-if="d == 4">Donnerstag: {{cat.donnerstag}}</h2> 
 
    <h2 ng-if="d == 5">Freitag: {{cat.freitag}}</h2> 
 
    <h2 ng-if="d == 6">Samstag: {{cat.samstag}}</h2> 
 
    <h2 ng-if="d == 0">Sonntag: {{cat.sonntag}}</h2> 
 
    </body>