我有一个JSON文件,其中将包含对象数组或字符串。我正在尝试根据存在的JSON类型显示它。

JSON文件,

场景1 JSON

"thing":{"important":"a giant banana"}


场景2 JSON

"thing":{"important":[
{"one":"one banana"},
{"two":"two banana"}
]}


所以我尝试了

<p ng-show='angular.isString(thing.important)'>Hey guy im a string</p>




<p ng-show="typeof thing.important === 'string'">Hey guy im a string</p>


但是当然都行不通,如何根据JSON(数组或字符串)的类型在ng-show中放置某些内容以进行显示

最佳答案

您无法直接在HTML上访问Javascript方法,因为$scope仅公开显示,并且您在{{}}中所做的任何尝试都可以在控制器的$scope中找到表达式并对其求值。

如果要直接在视图上访问Javascript上可用的对象/方法,则应使用将这些对象放入$scope属性,然后从UI对其进行访问。

的HTML

<p ng-show='angular.isString(thing.important)'>Hey guy im a string</p>


控制者

$scope.angular = angular; //but this is not preferred way to do it.


另一种方法是您可以在ng-show中调用该方法,该方法将与本机方法/对象进行通信。

的HTML

<p ng-show="checkStringType(thing.important)">Hey guy im a string</p>


控制者

$scope.checkStringType = function(val){
     return typeof val === 'string'; //preferred way to achieve this thing.
};

关于javascript - 尝试显示基于JSON类型的内容,没有带w/angular的 Controller ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34162559/

10-12 12:34
查看更多