简体   繁体   English

带有AngularJS和Ionic的JSON对象在ng-controller中的表达

[英]Expression in ng-controller for a JSON-Objects with AngularJS and Ionic

I parse JSON objects to create html elements. 我解析JSON对象以创建html元素。 In my case, I create from json file Buttons: 就我而言,我是从json文件中创建Buttons的:

{
    "type": "button",
    "id": "comButton",
    "icon": "ion-chatboxes",
    "name": "Communication",
    "onclick": "",
    "controller": "somemthctrl",
    "ngclick": "launchSomemethod()",
    "color": "white",
    "backgroundcolor": "#ff5db1",
    "font-size": "20px"
}

Controller: 控制器:

myApp.controller('generateButtonCtrl', function ($scope, $http) {
    $http.get('JSON/buttons.json').success(function(data){
        $scope.components = data;
    });
});

From the HTML page, I call the components from the json file: 在HTML页面中,我从json文件调用组件:

<a ng-repeat="component in components"
   style="color:{{component.color}}; background-color:{{component.backgroundcolor}} "
   id="{{component.id}}"
   class="{{component.type}}"
   href="{{component.onclick}}"
   ng-click="{{component.ngclick}}"
   ng-controller="{{component.controller}}">

    <i class="{{component.icon}}"><br></i>
    {{component.name}}
</a>

In the case ng-click="{{component.ngclick}}" und ng-controller="{{component.controller}}" will not be included. 如果不包含ng-click="{{component.ngclick}}"ng-controller="{{component.controller}}"

At the appropriate places I get from my editor WebStorm following error: Identifier or String literal or numeric literal expected. 在适当的地方,我从编辑器WebStorm收到以下错误: 标识符或字符串文字或数字文字。

I have a {{expression}} Problem. 我有一个{{expression}}问题。 How can I integrate the ng-controller and ng-click as a string from a json object? 如何集成ng-controllerng-click作为json对象中的字符串?

This is quite tricky. 这很棘手。 Angular team on their doc suggests that controller should be registered to a module while the DOM is being parsed. Angular团队在其文档中建议,控制器应在解析DOM时注册到模块。

All the $scope properties will be available to the template at the point in the DOM where the Controller is registered. 在模板中注册Controller的点上,所有$ scope属性都可用于模板。

Link: Angular controllers 链接: 角度控制器


  • Use $controllerProvider to register the controller This link shed's some light on how controllers are resolved at later point of the time, which might help you in designing your code as desired. 使用$ controllerProvider注册控制器该链接阐明了稍后如何解析控制器,这可能有助于您按需设计代码。
  • ng-click you can give an expression or a method which is inside the controller of $scope tree. ng-click,您可以在$ scope树的控制器内提供表达式或方法。 Both the expression and/or function search happens inside the $scope tree at the compile time of your template. 表达式和/或函数搜索都在模板编译时在$ scope树内进行。

Update As per the fiddler requested 根据提琴手的要求更新


I have corrected the fiddler code, removed unwanted lines, errors and made it working. 我已经纠正了提琴手的代码,删除了不需要的行,错误并使它正常工作。

Now your template is dynamic binding to the JavaScript code at the run-time. 现在,您的模板可以在运行时动态绑定到JavaScript代码。

Fiddler Link 提琴手链接

Javascript : Javascript

 var myApp = angular.module('starter', []);
myApp.config(['$sceDelegateProvider', function($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
        'self',
        'https://api.myjson.com/**'
    ]);
}]);

myApp.controller('generateHTMLCtrl', function ($scope, $http, $compile, $interpolate, $templateCache) {
    $http.get('https://api.myjson.com/bins/1gkh0').success(function (data) {      
        for(var i in data){
            var interpolated = $interpolate($templateCache.get("tpl").trim())(data[i]);            
            angular.element(document.querySelector("#loadhere")).append($compile(interpolated)($scope));            
        }               
    });
});

myApp.controller("OpenLinkCtrl", function ($scope) {    
        $scope.OpenLink = function () {
           alert("Link open");
        }    
});

Html : HTML

 <body ng-app="starter" class="padding" style="text-align: center">
 <div class="row responsive-md" ng-controller="generateHTMLCtrl" id="loadhere"></div>                                        
 <script type="text/ng-template" id="tpl">
                 <div class="col">
                    <a style="color:{{color}}; background-color:{{backgroundcolor}} "
                       id="{{id}}" class="{{type}}" href="{{topage}}" ng-controller="{{controller}}" ng-click="{{function}}"><i class="{{icon}}"><br></i>{{name}}</a>
                </div>
          </script>
    </body>

Explanation: 说明:

  • Used interpolate service 二手插值服务
  • Used compiler service 二手编译器服务

Note: Interpolator cannot parse on array of objects. 注意:插值器无法解析对象数组。 Hence used for loop to interpolate each oject array and append it to the DOM. 因此,用于循环来插入每个对象数组并将其附加到DOM。

More info on compiler and interpolation can be found here 有关编译器和插值的更多信息,请参见此处。

I'm not sure that it's possible the ng-controller could be a {{ expression }} . 我不确定ng-controller是否可能是{{ expression }} The workarround it's creating a function that returns the name of the controller that you want and you can assign to a var inside the controller... 它的工作环境是创建一个函数,该函数返回所需控制器的名称,您可以将其分配给控制器内部的var ...

In other case, why you want to use a different controller for each button? 在其他情况下,为什么要为每个按钮使用不同的控制器?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM