[英]ng-init with razor expression
我試圖渲染這樣的事情:
<thead ng-init="isDoctor = @(User.IsInRole("Doctor"))">
我希望它是“isDoctor = true | false”(我的服務器端代碼呈現此模板返回PartialView),順便說一下我總是得到如下錯誤: 語法錯誤:令牌'undefined'不是表達式的列null處的主表達式[ isDoctor =]從[isDoctor = at Error()]開始 。 那么,原因是什么?
試試這種方式:
<thead ng-init="isDoctor = @(User.IsInRole("Doctor") ? "true" : "false")">
因為C#boolean渲染了大寫的第一個字母:
<thead ng-init="isDoctor = True|False">
而True
或False
是不確定的
或者,您可以考慮以下事項:
<script type='text/javascript'>
angular.module('my-module')
.value('isDoctor', @(User.IsInRole("Doctor") ? "true" : "false"))
// perhaps other values that need passed in from the server?
.constant('aValue', '@Model.AValue') // for example
;
</script>
這不會像ng-init
那樣將值直接放在范圍內; 但是,它為您提供了一個可注入的值,您可以在控制器,服務,指令等中使用它,實際上是一個運行時配置變量:
// some script somewhere
angular.module('my-module').controller('myController', [
'$scope',
'isDoctor',
function($scope, isDoctor) {
$scope.isDoctor = isDoctor;
// other controller code here
}]);
關於從Razor到Angular傳遞數據的這種風格的isDoctor
在於,如果你忘記這樣做,Angular的依賴注入會拋出錯誤,因為實例化myController
需要定義isDoctor
。 它可能會發現可能很難找到的運行時錯誤,這個錯誤很難找到應該相對容易糾正的配置/編譯錯誤。
它還在Razor(cshtml)文件中為您提供了一個位置,在該文件中,您的服務器端參數將傳遞到Angular運行時,這樣不那么混亂,特別是如果您的HTML標記有很多指令和插值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.