I have a boolean variable in my cshtml file. When I try to pass it to my Angular directive, it is received as "False" instead of "false". If I hardcode it to "false" (lower case), it does not work either.
My cshtml file:
@{
var myVar = false;
}
<some-directive test="@myVar"></some-directive>
My test directive is like this:
angular.module('someApp')
.directive('someDirective', function () {
return {
restrict: 'E',
scope: {
test: '@'
},
link: function ($scope, element, attrs) {
console.log($scope.test) // False
console.log(!$scope.test) // false
console.log(!!$scope.test) // true
}
}
});
I have a boolean variable in my cshtml file. When I try to pass it to my Angular directive, it is received as "False" instead of "false". If I hardcode it to "false" (lower case), it does not work either.
My cshtml file:
@{
var myVar = false;
}
<some-directive test="@myVar"></some-directive>
My test directive is like this:
angular.module('someApp')
.directive('someDirective', function () {
return {
restrict: 'E',
scope: {
test: '@'
},
link: function ($scope, element, attrs) {
console.log($scope.test) // False
console.log(!$scope.test) // false
console.log(!!$scope.test) // true
}
}
});
Share
Improve this question
edited Apr 2, 2016 at 18:47
Zanon
30.8k21 gold badges118 silver badges126 bronze badges
asked Apr 2, 2016 at 18:38
rajeshrajesh
411 silver badge7 bronze badges
4 Answers
Reset to default 5You can find part of your answer here.
Specifically for Angular, use the directive variable as test: '='
instead of test: '@'
. With this, your variable will be parsed as a boolean with the value "false" and not as the text "false".
Also, in your Razor file, try the following to convert from "False" to "false":
@{
var myRazorVar = false;
}
<some-directive test="@myRazorVar.ToString().ToLower()"></some-directive>
@* or *@
<some-directive test="@Json.Encode(myRazorVar)"></some-directive>
Since both languages are case sensitive and uses different pattern for Boolean (even for numbers) you can use:
<some-directive test="@Json.Encode(myVar)"></some-directive>
Will format C# data to javascript accordingly.
your scope should be '=' not '@'
angular.module('someApp')
.directive('someDirective', function () {
return {
restrict: 'E',
scope: {
test: '='
},
link: function ($scope, element, attrs) {
console.log($scope.test) // false
console.log(!$scope.test) // true
console.log(!!$scope.test) // false
}
}
});
I was able to get it working like this:
let replicateReopeningClientFiles = @Json.Serialize(Model.ReplicateReopeningClientFiles);