在AngularJs中显示来自响应的Div

时间:2014-10-21 02:25:13

标签: javascript jquery html angularjs

问题 -

我在AngularJs中有一个Controller,它执行$ 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);

}());

2 个答案:

答案 0 :(得分:3)

我假设你要做的是渲染返回的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>

答案 1 :(得分:1)

正如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>