作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我希望能够在 Controller 中使用部分 URL,在这种情况下能够根据 URL 设置主体类,但我还想使用服务从 json 中获取其他信息基于该 URL 的文件。
如果我使用 console.log 通过 for 循环检查 $scope.pageDetail.id 中的内容,我会得到正确的响应,但它在 for 之外返回“未定义” 循环。一切都在页面重新加载时有效,但当我使用页面的导航点击我的方式浏览 url 时却不行。
我的 Controller :
oddproto.controller('UrlController', function($scope, $location, PageService){
// Get page id from URL
var pageId = $location.path().replace("/", "");
$scope.pageDetail = PageService.query(function(data) {
// Get the correct page details from the dataset
for (var i = 0; i < data.length; i++) {
if (data[i].id === pageId) {
$scope.pageDetail = data[i];
break;
}
}
});
})
我的服务
oddproto.factory('PageService', function($resource) {
return $resource('includes/pages.json');
});
pages.json
[
{
"id": "blog",
"name": "Blogg"
},
{
"id": "cases",
"name": "Projekt"
},
{
"id": "contact",
"name": "Kontakt"
}
]
我也试过在没有服务的情况下这样做,即
$scope.pageDetail = $location.path().replace("/", "");
但这也只适用于页面加载,所以在我看来 $location 是这里的问题。不过我不知道我还能用什么。
最佳答案
您的 Controller 无法识别位置变化。初始化 Controller 时,它会设置页面 ID,但更改后,您的 Controller 不会重新初始化。为此,您应该使用
scope.location=$location;
scope.$watch('location.path()', function(path) {
$scope.pageDetail = ....
});
这将观察 location.path() 并且如果它发生变化,它会执行您的自定义魔法。
此外,我建议你让你的 Controller 成为一个指令,因为它只处理你的 body-tag 的样式。
关于angularjs - Angular js : How to use URL path in a controller to populate scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16559434/
我是一名优秀的程序员,十分优秀!