1

我正在使用MEAN.js生成器和我在網上找到的教程構建應用程序。在這裏我有一個日期選擇器在我的一個角度的意見。現在我想要識別ng-change指令並做一些事情。在我更改日期時,我的測試警報沒有被調用。Ang-ng不會調用代碼。我是否使用錯誤的模型

<div class="form-group"> 
    <label class="control-label" for="statusdate">Status Date</label> 
    <div class="controls"> 
     <input type="date" ng-change="alert('something')" data-ng-model="statusDate" id="statusdate" class="form-control"> 
    </div> 
</div> 

有人可以幫忙嗎?我是Angular的新手。

另外,我讀了一些地方,可能是因爲我使用了data-ng-model而不是ng-model。情況會是這樣嗎?如果是這樣,那麼兩者有什麼區別?

回答

2

您正在執行控制器中不存在的方法。

嘗試這樣創造的:

$scope.alert = function(msg) { 
    alert(msg); 
}; 
+0

看起來更像是這樣,但是你的建議工作: $ scope.alert = function(){ alert(); }; – user2623706

3

啊,問題是,你沒有你認爲你做的上下文。

在Javascript中幾乎無處不在,所有關閉的根都是window,其中包含alert()

幾乎到處都是,但並非到處都是。不在評估ng-change()的環境中。例如,您可以通過創建一個控制器來爲$scope添加一個名爲alert的值,並將其指向window.alert

<div class="form-group"> 
    <label class="control-label" for="statusdate">Status Date</label> 
    <div class="controls" ng-controller="myController"> 
     <input type="date" ng-change="alert('something')" data-ng-model="statusDate" id="statusdate" class="form-control"> 
    </div> 
</div> 

然後在使用Javascript:

angular.module("MyApp") 
.controller("myController", ['$scope', '$window', function($scope, $window) { 
    $scope.alert = $window.alert; 
}]); 

編輯:你可以使用的只是window代替$window,因爲window可以在這裏找到,但是,這將使你的代碼更難以測試的長遠來看。

0

問題是ng-change期待一個表達式,但是你給它一個函數名alert()來顯示字符串「something」,因此它不知道該怎麼做。

一個可能的解決方案是添加這個在HTML文件

<script> 
    angular.module('Your_App_Name', []) 
    .controller('YourControllerName', ['$scope', '$window', function($scope, $window) { 
     $scope.alert = function(message) { 
      $window.alert(message); 
     }; 
    }]); 
</script> 

參考文檔,瞭解有關如何使用NG-變化更多信息的頂部 https://docs.angularjs.org/api/ng/directive/ngChange

參考difference b/w ng-model and data-ng-model到了解data-ng-model和ng-model之間的區別。他們都應該工作得很好。

+0

我想指出你的答案有兩個問題。首先,你不解釋_why_' alert()',這是否是幾乎普遍知道的,在這裏是未知的;其次,你沒有(明顯的)理由「包裝」警報功能。另一方面,你使用'$ window'是有啓發意義的,所以我會爲了我的回答而偷取它。 [邪惡的笑聲] – Malvolio

相關問題