我正在尝试填充一个ion-content
容器。我想根据用户单击的选项卡将 HTML 加载到$scope
中:
<ion-tabs tabs-type="tabs-icon-only">
<ion-tab ...>
<ion-tab title="Create" icon-on="ion-android-create">
<ion-content padding="true" class="has-header">
{{getCreate}}
</ion-content>
</ion-tab>
<ion-tab ...>
</ion-tabs>
这是此视图的控制器:
(function () {
'use strict';
angular.module('ionicApp')
.controller('HomePageController', ['$scope', '$state', '$templateCache', HomePageController]);
function HomePageController($scope, $state, $templateCache) {
$scope.getCreate = function() {
// at the moment create.html is just simple static html.
return $templateCache.get('app/views/home/ads/create.html');
//return $templateCache.get('main.create'); // this also doesn't work
};
}
})
();
这两个相关状态定义为:
.state('main.home', {
url: '/home',
views: {
'main': {
templateUrl: 'app/views/home/home.html',
controller: 'HomePageController'
}
}
})
.state('main.create', {
url: '/create',
views: {
'main': {
templateUrl: 'app/views/home/ads/create.html',
controller: 'CreateAdController'
}
}
})
我这样做做错了吗?我需要做什么才能将create.html
加载到HomePageController
中的$scope.getCreate
中?
你的方法对我来说似乎有点太复杂了。首先,您必须确保您的模板已加载到$templateCache。仅当模板首次在应用中的某个位置呈现时(例如,通过使用"templateUrl"属性),才会发生这种情况或者,您可以通过自己的 ajax 调用从文件中获取数据,并使用给定的$interpolate编译它,$compile Angular 中的函数。但话又说回来:对于这种情况来说,这似乎太复杂了。
其次,你必须使用ng-bind-html,因为你这样做的方式会看到经过净化的html。 所以会有这样的东西 等,而不是它的编译 HTML 版本。
也许你应该简单地使用 ng-include 指令,一切都会在眨眼间
正如@Patrick Kelleter所提出的,你的方法过于复杂,包括手动使用$templateCache和编译HTML。
为什么不按照设计的方式使用路由器?
首先,重命名状态的视图,以便可以显式引用它:
.state('main.create', {
url: '/create',
views: {
'create': {
templateUrl: 'app/views/home/ads/create.html',
controller: 'CreateAdController'
}
}
})
然后使用选项卡上的ui-sref=
更改状态,并使用具有特殊命名视图的<ion-nav-view ...>
插入状态的模板。
<ion-tabs tabs-type="tabs-icon-only">
<ion-tab ...>
<ion-tab title="Create" icon-on="ion-android-create" ui-sref="main.create">
<ion-content padding="true" class="has-header">
<ion-nav-view name="create"></ion-nav-view>
</ion-content>
</ion-tab>
<ion-tab ...>
</ion-tabs>
然后,当单击选项卡时,路由器会将app/views/home/ads/create.html
的内容插入<ion-nav-view name="create">
元素中。
下面是完整的演练:使用导航和路由构建应用 - 第 1 部分
只需使用 $http.get
:
$http.get($scope.template.url).then (function(response) {
console.log(response);
$scope.contents = response.data;
});
PLNKR上的演示。
浏览器的同源策略和跨源资源共享 (CORS) 策略可能会限制模板是否成功加载。