从字符串变量设置ng-click属性值

时间:2017-03-23 14:04:59

标签: javascript angularjs angularjs-1.6

我有一个外部JSON文件,它是像这样的按钮/动作的集合

   {  
   "foo1":{  
      "name":"productDetails",
      "displayAs":"button",
      "action":"viewDetails()"
   },
   "foo2":{  
      "name":"sell",
      "displayAs":"button",
      "action":"sellProduct()"
   }
}

稍后,在我看来,我为该JSON中包含的每个对象使用ng-repeat创建<div>

我的问题是,我可以像这样在JSON文件中设置ng-click属性吗?

<li ng-repeat = "field in fields">
    <div ng-click = field.action > {{field.name}} </div>
</li>

1 个答案:

答案 0 :(得分:1)

您可以使用ng-bind-html执行此操作。

 <li ng-repeat = "field in fields">
    <div bind-html-compile ng-bind-html="trust(field)"  >  </div>
  </li>

添加bind-html-compile指令以编译DOM,以便更改将对DOM元素产生影响

指令

 .directive('bindHtmlCompile', ['$compile', function($compile) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            scope.$watch(function() {
                return scope.$eval(attrs.bindHtmlCompile);
            }, function(value) {
                element.html(value);
                $compile(element.contents())(scope);
            });
        }
    };
 }]);

trust函数中,将对象作为参数传递并返回html信任元素

 $scope.trust = function(html) {
    return $sce.trustAsHtml('<div ng-click = "' + html.action + '" > {{field.name}} </div>');
 }

演示

angular.module("app",[])
.controller("ctrl",function($scope,$sce){

$scope.viewDetails = function(){console.log("viewDetails")}
$scope.sellProduct = function(){console.log("sellProduct")}
$scope.fields =    {  
   "foo1":{  
      "name":"productDetails",
      "displayAs":"button",
      "action":"viewDetails()" 
   },
   "foo2":{  
      "name":"sell",
      "displayAs":"button", 
      "action":"sellProduct()"
   }
}

$scope.trust = function(html){

return $sce.trustAsHtml('<div ng-click = "'+html.action+'" > {{field.name}} </div>');

}


}).directive('bindHtmlCompile', ['$compile', function ($compile) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                scope.$watch(function () {
                    return scope.$eval(attrs.bindHtmlCompile);
                }, function (value) {
                    element.html(value);
                    $compile(element.contents())(scope);
                });
            }
        };
    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <li ng-repeat = "field in fields">
    <div bind-html-compile ng-bind-html="trust(field)"  >  </div>
</li>
</div>