显示AngularJs中响应的Div

Display Div from response in AngularJs

本文关键字:Div 响应 AngularJs 显示      更新时间:2023-09-26

问题问题——

我在AngularJs中有一个控制器,它执行$http.get,作为响应,它获得数据(它也有HTML DivID和.Class)。我如何从响应中获取这个DivID并将其传递到AngularJs中的视图?

我的代码----

Controller.js

  $scope.init = function(){
            console.log("I am working")
                UserService.signIn()
                    .success(function (response) {
                        console.log(response) //this display everything such as divID and .Class
                        //Want this divID and pass it to my view
                    })
                    .error(function (status, data) {
                    })
        };$scope.init();

Services.js

(function() {
    var UserService = function($http) {
        var urlBase = 'http://www.corsproxy.com/myWebsite.com';
        var factory = {};
        factory.signIn = function() {
            return $http.get(urlBase);
        };
        return factory;
    };
    UserService.$inject = ['$http'];
    angular.module('app').factory('UserService',UserService);
}());

我假设您要做的是呈现返回的html,而不是在UI中打印html内容。

在这种情况下,您可以像一样使用ngBindHTML指令

var app = angular.module('my-app', ['ngSanitize']);
app.controller('MyController', ['$scope',
  function($scope) {
    $scope.myhtml = '<div class="myclass">some content</div>'
  }
])
.myclass {
  color: red;
}
<script src="https://code.angularjs.org/1.2.9/angular.js"></script>
<script src="https://code.angularjs.org/1.2.9/angular-sanitize.js"></script>
<div ng-app="my-app" ng-controller="MyController">
  <div>{{myhtml}}</div>
  <div ng-bind-html="myhtml"></div>
</div>

根据Arun的建议,您需要一个指令。似乎您想将在其他地方检索到的HTML传递给视图(而不是指令自己获取HTML)。我想你可以创建一个从HTML中提取内容的指令。

app.directive("find", function($compile){
  var html = "";
  var selector = "";
  // use jQuery to construct an object from html and .find using the selector
  function render(scope, elem){
    if (html === "") return;
    var jqHtml = angular.element("<div>").html(html).find(selector);
    elem.empty();
    elem.html(jqHtml.html());
    // $compile, such that any directives/expressions in the imported HTML 
    //are compiled and linked to the right scope
    $compile(elem.contents())(scope);
  }
  return {
    restrict: "E",
    scope: true,
    link: function(scope, elem, attrs){
      // $observe the attributes for changes
      attrs.$observe('selector', function(newValue){
        selector = newValue;
        render(scope, elem);
      });
      attrs.$observe('html', function(newValue){
        html = newValue;
        render(scope, elem);
      });
    }
  };
});

用法是:

<find html="{{html}}" selector="#t1"></find>