2016-11-15 19 views
0

如果我設置了$scope.true = false;,我期望引用true的Angular表達式評估爲false。同樣,我期望和$scope.undefined = true產生類似的結果。

殘暴的命名,爲什麼不這些工作?在角碼中的哪個位置確定$scope屬性是否會被引用?

var myApp = angular.module('myapp', []); 
 

 
myApp.controller('myctrl', function($scope) { 
 

 
    $scope.foo = "bar"; 
 
    
 
    $scope.true = false; 
 
    $scope.true2 = false; 
 
    
 
    $scope.false = true; 
 
    $scope.false2 = true; 
 
    
 
    $scope.undefined = true; 
 
    $scope.undefined2 = true; 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myapp" ng-controller="myctrl"> 
 
    <p>{{ foo }}</p> 
 
    <div ng-show="true"> 
 
    $scope.true is equal to false here. ng-show should hide this. 
 
    </div> 
 
    <div ng-show="true2"> 
 
    $scope.true2 is equal to false here. ng-show hides this. 
 
    </div> 
 
    <div ng-hide="false"> 
 
    $scope.false is equal to true here. ng-hide should hide this. 
 
    </div> 
 
    <div ng-hide="false2"> 
 
    $scope.false2 is equal to true here. ng-hide hides this. 
 
    </div> 
 
    <div ng-hide="undefined"> 
 
    $scope.undefined is equal to true here. ng-hide should hide this. 
 
    </div> 
 
    <div ng-hide="undefined2"> 
 
    $scope.undefined2 is equal to true here. ng-hide hides this. 
 
    </div> 
 
</div>

回答

1

只用了快看,但是這有什麼角的解析器認爲是「文字」的事情。角度分析器將表達式分解爲單個令牌並構建抽象語法樹。基本上它會檢查文字的映射來確定令牌是什麼。

var literals = { 
    'true': true, 
    'false': false, 
    'null': null, 
    'undefined': undefined 
    }; 

你可以看到更多的解析器代碼在這裏:https://github.com/angular/angular.js/blob/master/src/ng/parse.js

雖然我不知道你是想用引用爲假(除了迷惑大家)真正實現的目標,你應該能夠定製使用解析提供商文字值:$parseProvider.addLiteral(name, value)

你也可以解決這個問題,通過使用控制器的語法:

<div ng-controller="ctrl as vm"> 
... 
<span ng-if="vm.false">Is shown</span> 
... 
</div> 
... 
function Ctrl() { 
    this.false = true; 
} 
+1

我永遠不會編碼這個,但想知道發生了什麼。你的解釋正是我正在尋找的。謝謝! – adamdport

相關問題