2017-05-10 62 views
0

我想在變量中創建<select ng-model='selected' ng-options='stage as stage.name for stage in stages'></select>元素作爲字符串。正如你在這裏看到的,select元素中有ng -...屬性。如果我使用沒有ng -...屬性的select元素,它顯示沒有問題。如果我在其中使用ng -...,它不會顯示任何內容。那麼,如何讓它與ng -...一起顯示呢?請幫忙。如何使用ng -...屬性綁定html代碼

我的html代碼:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8" /> 
    <script src="Scripts/angular.min.js"></script> 
    <script src="Scripts/angular-sanitize.js"></script> 
    <script src="Scripts/myScripts/index.js"></script> 
</head> 
<body> 
    <div ng-app="myapp" ng-controller="myCtrl"> 
     <div ng-bind-html="htmlCode"> 
     </div> 
    </div> 
</body> 
</html> 

我的js代碼:

var app = angular.module('myapp', ['ngSanitize']); 

app.controller('myCtrl', ["$scope", function ($scope) { 

    $scope.stages = 
     [{ name: "Identification of Discontinuing Factors", value: 1 }, 
     { name: "Project Level Assessment", value: 2 }, 
     { name: "Organizational Readiness Assessment", value: 3 }]; 

    $scope.htmlCode = "<select ng-model='selectedStage' ng-options='stage as stage.name for stage in stages'></select>"; 
}]); 

回答

1

你需要重新編譯DOM爲了工作ng-屬性。使用此僞指令作爲ng-bind-html元素的屬性。

.directive('dynamic', function ($compile) { 
    return { 
    restrict: 'A', 
    replace: true, 
    link: function (scope, ele, attrs) { 
     scope.$watch(attrs.dynamic, function(html) { 
     ele.html(html); 
     $compile(ele.contents())(scope); 
     }); 
    } 
    }; 
}); 

演示

var app = angular.module('myapp', []); 
 

 
app.controller('myCtrl', ["$scope","$sce", function ($scope,$sce) { 
 

 
    $scope.stages = 
 
     [{ name: "Identification of Discontinuing Factors", value: 1 }, 
 
     { name: "Project Level Assessment", value: 2 }, 
 
     { name: "Organizational Readiness Assessment", value: 3 }]; 
 

 
    $scope.htmlCode = "<select ng-model='selectedStage' ng-options='stage as stage.name for stage in stages'></select>"; 
 
    
 
    $scope.trust = function(html){ 
 
     return $sce.trustAsHtml(html) 
 
    } 
 
}]); 
 

 
app.directive('dynamic', function ($compile) { 
 
    return { 
 
    restrict: 'A', 
 
    replace: true, 
 
    link: function (scope, ele, attrs) { 
 
     scope.$watch(attrs.dynamic, function(html) { 
 
     ele.html(html); 
 
     $compile(ele.contents())(scope); 
 
     }); 
 
    } 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myapp" ng-controller="myCtrl"> 
 
     <div ng-bind-html="trust(htmlCode)" dynamic> 
 
     </div> 
 
     
 
     {{selectedStage}} 
 
    </div>