Lan*_*ara 4 javascript json router angularjs
我知道这是一个构造不良的问题,但我不知道怎么回答它.
我是AngularJS的新手,我试图基本上说"如果用户点击"这个"个人资料",请转到/models/{{ model.id }}model.id是被点击的"此"个人资料的价值.
基本上,main.html只有一些信息(如果你愿意,只有一个片段),当点击一个配置文件时,它应该转到/models/{{ model.id }}然后显示完整的配置文件,而不仅仅是一个片段.
到目前为止我的工作原理是,当悬停配置文件链接时它会显示正确的ID,并使用正确的url参数进入正确的视图,但是如何在视图中写入数据,以便数据将会出现与点击的ID相关?我通常用PHP/Laravel和MySQL来做这个,但我想用Angular来试试.
app.js:
'use strict';
angular
.module('swoleincApp', [
'ngRoute',
'ngSanitize',
'ngAnimate'
])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/models', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/models/:id', {
templateUrl: 'views/individual.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/models'
});
$locationProvider.html5Mode(true);
}]);
Run Code Online (Sandbox Code Playgroud)
MainCtrl.js:
'use strict';
angular
.module('swoleincApp')
.controller('MainCtrl', ['$scope', '$http', MainCtrl]);
function MainCtrl($scope, $http) {
$http.get('storage/models.json').success(function(data) {
$scope.models = data;
});
}
Run Code Online (Sandbox Code Playgroud)
main.html中:
<div class="model-container" ng-repeat="model in models">
<a href="/models/{{ model.id }}">
<div class="row">
<div class="col-sm-2">
<div class="model-profile-image">
<img ng-src="{{ model.profileImage }}" width="100" height="100">
</div>
</div>
<div class="col-sm-8">
<div class="model-stats">
<h3>{{ model.name }}, {{ model.age }}, {{ model.height }}, {{ model.weight }}.</h3>
</div>
<div class="model-motto">
<p>{{ model.motto }}</p>
</div>
</div>
</div>
</a>
</div>
Run Code Online (Sandbox Code Playgroud)
models.json(假装"其他东西"是指个人简介):
{
"1": {
"id": "1",
"profileImage": "../img/dom.jpg",
"name": "Dom",
"age": "19",
"height": "6'2",
"weight": "170lbs",
"motto": "My name is dom and I'm a 19 year old bodybuilder from Russia.",
"other": "other stuff",
"other": "other stuff",
"other": "other stuff",
"other": "other stuff",
},
"2": {
"id": "2",
"profileImage": "../img/Tom.jpg",
"name": "Tom",
"age": "21",
"height": "5'8",
"weight": "190lbs",
"motto": "I'm Tom. Everyone knows my name. Everyone knows my game.",
"other": "other stuff",
"other": "other stuff",
"other": "other stuff",
"other": "other stuff",
}
}
Run Code Online (Sandbox Code Playgroud)
使用不同的控制器来简化此操作.:id可以使用$routeParams注入控制器访问该参数.
angular
.module('swoleincApp')
.controller('ProfileCtrl', ['$scope', '$http','$routeParams', ProfileCtrl]);
function ProfileCtrl($scope, $http, $routeParams) {
$http.get('storage/models.json').success(function(data) {
$scope.profile= data[$routeParams.id];
});
}
Run Code Online (Sandbox Code Playgroud)
请务必更新此控制器的路由配置.
通常,您将创建一个服务来处理检索数据并存储它.$http现在离开,保持简单.
建议通过文档站点上的phoneCat教程.这是路由部分的链接