繁体   English   中英

在角度模板中将HTML页面添加到div

[英]Add Html page to div in angular template

我有角模板,其中有一个div。 我试图基于$ watch将html视图(.html)页面加载到div。 视图已正确加载,但未附加到$ scope对象。 这是我的控制器,我只发布了加载html视图的代码部分。

var filtertemplate = "#locationChart_right";
$scope.templateUrl = '/_layouts/AngularControls/MyController/Views/MyChart.html';
$scope.$watch("currentItem", function () {

$scope.currentConfig = $rootScope.currentItem;
LocDetailsChartService.getUserPrefs()
.then(function (response) {
    var data = response.data.ChartsUserPrefs;
    $scope.MeritType = data.MeritType;
    if ($scope.MeritType !== undefined) {
        if ($scope.MeritType == "Score") {
            $(filtertemplate).load("/_layouts/AngularControls/MyController/Views/MyScoreChart.html");
            $scope.$apply()
        }
        if ($scope.MeritType == "Potential") {
            $(filtertemplate).load("/_layouts/AngularControls/MyController/Views/MyPercentChart.html");
            $scope.$apply()
        }
    }
   // $scope.radioButtonHandler($scope.MeritType);
});
});

HTML

有人可以建议我在哪里做错吗?

好吧,您正在将jQuery与Angular混合使用,看来您不应该这样做。

您可以使用ng-include以更简单的方式将html模板动态加载到页面中。

假设您有一个div

<div id='locationChart_right'></div> <!-- traditionally you use an id to find this div and replace the content... the jQuery way -->

但是使用Angular,您只需使用ng-include分配变量即可更改模板。

<div ng-include="templateToLoad"></div>

现在,在您的JS中,您只需要一个$ scope变量来分配要加载的模板。

LocDetailsChartService.getUserPrefs()
.then(function (response) {
    var data = response.data.ChartsUserPrefs;
    $scope.MeritType = data.MeritType;
    if ($scope.MeritType !== undefined) {
        if ($scope.MeritType == "Score") {
            $scope.templateToLoad =  "/_layouts/AngularControls/MyController/Views/MyScoreChart.html";
        }
        if ($scope.MeritType == "Potential") {
            $scope.templateToLoad = "/_layouts/AngularControls/MyController/Views/MyPercentChart.html";
        }
    }
});

这将自动加载适当的模板并更新视图中的范围对象。

如果出于任何原因需要保留jQuery方式,则需要在元素上强制执行$ compile以更新$ scope值。

像这样:

$compile($(filtertemplate)($scope);

在上下文中:

if ($scope.MeritType == "Potential") {
    $(filtertemplate).load("/_layouts/AngularControls/MyController/Views/MyPercentChart.html");
        $compile($(filtertemplate))($scope);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM