使用来自我的控制器的数据编译 html 模板

Compile an html template with data from my controller

本文关键字:数据 编译 html 模板 控制器 自我 我的      更新时间:2023-09-26

在Angular中,我正在为一家拥有不同房间的酒店构建一个网络应用程序。我希望能够单击导航栏中的选项卡(或页面上的任何位置(,并使用有关我存储在控制器中的房间的公共数据填充 html 视图。最好的方法是什么?我正在使用 ui 路由。我还没有找到关于堆栈溢出的详尽答案。

下面是我的应用外观的示例。

这是我的应用程序.js

var appBB = angular
.module('appBB', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', MainRouter]);
function MainRouter(states, router) {
    states
    .state( 'home', {
      url:'/',
      templateUrl: 'home.html'
  }).state( 'show',{
      url:'/show',
      templateUrl:'show.html'
  });
    router.otherwise('/');
}

这是我的控制器

appBB.controller("BBController", BBController());
function BBController() {
    var self = this;
    self.apartments = [
        {
        name: "apt1",
        image: "imag1.jpg"
        amenities: ["blablabal", "bhuhuih", "hvjf"]
        },
        {
        name: "apt2",
        image: "img2.jpg",
        amenities: ["blablabla", "bkjhkg", "lkhug"]
        },
        {
        name: "apt3",
        image: "img3.jpg",
        amenities: ["blablabla", "jgfkhgc","jgvkhg"]
        }
    ]
}

这是我想要填充的视图模板的示例:

<div ng-controller="BBController as bbs">
    <div>
         <h4>{{this should show the apt name}}</h4>
    </div>
    <div class="row">
         <div class="col-sm-8">
               <img ng-src="{{this should show the image of the apt that i  clicked on}}" />                     
         </div>
         <div class="col-sm-4">
             <ul>
               <li ng-repeat="looping over the apt amenities">{{amenity}}</li>              </ul>
         </div>          
    </div>
</div>

任何帮助将不胜感激。

你正在做的事情看起来不错,但你需要一些改进。我建议您在导航栏单击上使用$routeParams。像这样:

<div ng-controller="BBController as bbs">
<div>
     <h4>{{this should show the apt name}}</h4>
</div>
<div class="row">
     <div class="col-sm-8">
           <img ng-src="{{this should show the image of the apt that i  clicked on}}" />                     
     </div>
     <div class="col-sm-4">
         <ul>
           <li ng-repeat="amemity in amenities">
            <a ng-href="#amemityList/{{ amemity.id }}"> {{amemity.name}} </a>
           </li> 
         </ul>
     </div>          
</div>

现在,您可以使用此amenity.id传递给YourController并相应地获取相应的视图以及该"单击"amenity.id的所有信息

.when('/amemityList/:navBar', {
            templateUrl: "AmenityView.html",
            controller: "YourController"
        })

这样,您将能够使用单视图AmenityView.html并且其信息可以根据您的amenity.id传递给控制器,例如

var navBarSelection_id = $routeParams.navBar;

也许,您可以在/show/apt1 等 url 中添加信息,并使用 apt1 在控制器上查找信息。

编辑:

一点解释:https://docs.angularjs.org/tutorial/step_07