2016-11-04 48 views
1

我有一個divNG-init的不NG,如果

<div class="error-text" ng-if="customerIdLength > customerIdMaxLength" ng-init="error='yes'" >Error presented</div>

這裏ng-if工作是否正常工作。

基於ng-init值我正在禁用按鈕是這樣的:

<button class="btn btn-success" type="submit" ng-click="submitNumber();" ng-disabled="error=='yes'">Submit</button> 

這是行不通的。 如果我把這ng-init某些其他元素沒有ng-if然後它工作正常。那麼背後的原因是什麼?

+0

使用'NG隱藏/ NG-show'這些創建DOM元素,但隱藏/顯示根據條件將invoke' NG- init'但ng-if將停止創建將停止ng-init調用的DOM元素 –

+0

我已經嘗試過'ng-show/ng-hide',但問題是我的按鈕在隱藏和顯示條件中都將被禁用。 –

+0

@Arpit Meena,所以,你想要顯示錯誤文本時禁用按鈕,但是當錯誤文本被隱藏時,必須啓用按鈕? – Natiq

回答

0

ng-ifng-show之間的區別是,實際上ng-if去除從DOM連接到它的HTML元素,引起你的ng-init表達不被執行。

只需通過ng-show替換它應該做的伎倆

<div class="error-text" ng-show="customerIdLength" ng-init="error='yes'">Error presented</div> 
1

<!DOCTYPE html> 
 
<html data-ng-app="myApp"> 
 

 
<head> 
 
    
 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script> 
 
    
 
</head> 
 

 
<body data-ng-controller="testController"> 
 

 
    <div class="error-text" ng-init="$parent.error='yes'" ng-if="1 > 0">Error presented</div> 
 

 
    <button class="btn btn-success" type="submit" ng-click="submitNumber();" ng-disabled="error=='yes'">Submit</button> 
 

 
    <script> 
 
    // Code goes here 
 

 
    angular 
 
     .module('myApp', []) 
 

 
    .controller('testController', ['$scope', 
 
     function($scope) { 
 

 
     } 
 
    ]) 
 
    </script> 
 

 
</body> 
 

 
</html>

你需要使用$父得到NG,如果內側內範圍。

+0

禁用正在工作現在如何啓用隱藏錯誤上的按鈕? –

+0

只需將ng-if條件更改爲false,並參閱 –

+0

或將$ parent.error設置爲somethingelse –

0

我認爲邏輯是合理的,但它可能會缺少一些angularjs設置和配置,如ng-app和ng-controller聲明在標記中。

確保這是在頂部

宣佈
<div ng-app="github" ng-controller="githubRepos"> 
<!-- Your code --> 
</div> 

Solution