admin管理员组

文章数量:1331895

I am trying to render the thing like this:

<thead ng-init="isDoctor = @(User.IsInRole("Doctor"))">

I expect it to be "isDoctor = true|false" (my server side code renders this template returning PartialView), btw I always get an error like: Syntax Error: Token 'undefined' not a primary expression at column null of the expression [isDoctor =] starting at [isDoctor = at Error ()]. So, what is the reason for that?

I am trying to render the thing like this:

<thead ng-init="isDoctor = @(User.IsInRole("Doctor"))">

I expect it to be "isDoctor = true|false" (my server side code renders this template returning PartialView), btw I always get an error like: Syntax Error: Token 'undefined' not a primary expression at column null of the expression [isDoctor =] starting at [isDoctor = at Error ()]. So, what is the reason for that?

Share Improve this question edited Dec 13, 2013 at 10:17 starbeast asked Dec 13, 2013 at 9:57 starbeaststarbeast 1033 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Try this way:

<thead ng-init="isDoctor = @(User.IsInRole("Doctor") ? "true" : "false")">

Because C# boolean renders with capital first letter:

<thead ng-init="isDoctor = True|False">

And True or False is undefined

Alternatively, you might consider the following:

<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>

This doesn't put the value directly onto the scope like ng-init does; however, it gives you an injectable value that you can use in your controller, services, directives, etc. that is, effectively, a run-time configuration variable:

// some script somewhere
angular.module('my-module').controller('myController', [
    '$scope',
    'isDoctor',
    function($scope, isDoctor) {
        $scope.isDoctor = isDoctor;

        // other controller code here
    }]);

The nice part about this style of passing data from Razor to Angular is that Angular's dependency injection will throw an error if you forget to do this, since instantiating myController requires isDoctor to be defined. It moves what could potentially be a runtime error that's hard to find into a config/pile error that should be relatively easy to correct.

It also gives you a single place in your Razor (cshtml) file where your server-side parameters get passed into the Angular runtime, which is less messy, especially if your HTML markup has lots of directives and interpolation.

本文标签: javascriptnginit with razor expressionStack Overflow