簡體   English   中英

AngularJS:ng-bind-html取決於變量

[英]AngularJS : ng-bind-html depending on variable

我想在場景中顯示一些html(一個男人或一個女人的圖像),具體取決於登錄我網站的人的性別。 當我靜態定義“ imageToLoad”時,指令ng-bind-html起作用。 但是,如果我要綁定的html是由函數定義的,則無法使用。

控制台告訴我: TypeError:$ scope.getHtml不是函數

這是我的簡化代碼:

HTML:

<div id="img-container" ng-controller="sceneCtrl" ng-bind-html="imgToLoad">
</div>

JS:

.controller('sceneCtrl', function($scope, $http, $sce){
    /* This works
    ** $scope.imgToLoad = $sce.trustAsHtml('<img id="over2" src="imgMale.png"/>');
    */

    $scope.imgToLoad=$scope.getHtml();

    $scope.getHtml=function(){

      var gender='male';
      if(gender=='male'){
        return $sce.trustAsHtml('<img id="over2" src="imgMale.png"/>');
      }
      else if(gender=='female'){
        return $sce.trustAsHtml('<img id="over2" src="imgFemale.png"/>');
      }
      return 'error getHtml';
    }
})

我用一個表示性別的變量簡化了JS,但最終,性別將由后端從數據庫給出。

根據我的研究,我可能必須使用“編譯”,但是我不知道它是如何工作的。

謝謝你的幫助 !

這里的問題是在初始化它之前,您正在調用$scope.getHtml ,因此在您調用該值時未定義。

不要在$scope放入函數,除非您在那里需要它們,並且當可以直接調用它們時,不要通過javascript通過$scope調用它們。 這應該工作:

.controller('sceneCtrl', function($scope, $http, $sce){

    $scope.imgToLoad = getHtml();

    function getHtml(){

      var gender='male';
      if(gender=='male'){
        return $sce.trustAsHtml('<img id="over2" src="imgMale.png"/>');
      }
      else if(gender=='female'){
        return $sce.trustAsHtml('<img id="over2" src="imgFemale.png"/>');
      }
      return 'error getHtml';
    }
})

使用自定義指令ng-html

演示: http : //jsfiddle.net/AntonWebDev2012/mb4nv5my/

.directive('ngHtml', [ '$compile', function ($compile) {
    return function (scope, elem, attrs) {
      if (attrs.ngHtml) {
        elem.html(scope.$eval(attrs.ngHtml));
        $compile(elem.contents())(scope);
      }
      scope.$watch(attrs.ngHtml, function (newValue, oldValue) {
        if (newValue && newValue !== oldValue) {
          elem.html(newValue);
          $compile(elem.contents())(scope);
        }
      });
    };
  } ]);

直接html起作用,所以問題是:函數在初始化之前被調用,請嘗試在之后調用。 例如。 $scope.getHtml=function(){ } $scope.imgToLoad=$scope.getHtml();

我的代碼在這里..我做了一些更改..

.controller('sceneCtrl',['$scope','$http','$sce', function($scope, $http, $sce) {

var gender='male';
$scope.getHtml=function(){
  if(gender=='male'){
    return $sce.trustAsHtml('<h3>Pablo</h3><img id="over2" src="http://www.freeiconspng.com/uploads/male-icon-19.png"/>');
  }
  else if(gender=='female'){
    return $sce.trustAsHtml('<h3>Picaso</h3><img id="over2" src="http://weknowyourdreams.com/images/female/female-01.jpg"/>');
  }
  return 'error getHtml';
}; 
 $scope.imgToLoad = $scope.getHtml();


 }]);

})(window.angular);

首先,我聲明getHTML函數,然后調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM