我已经创建了一个指令
app.directive('projects', ['projectServices',
function(projectServices) {
var projectController = function() {
var proj = this
projectServices.getProjects()
.success(function(result) {
proj.projects = result.data
proj.projects.map(function(project) {
project.showDetails = false
})
})
.error(function(err) {
console.log('error ' + err)
})
this.toggleProjectDetails = function(project) {
project.showDetails = !project.showDetails
}
}
return {
restrict: 'E',
templateUrl: '/partials/project',
controller: projectController,
controllerAs: 'projectCtrl'
}
}
])
模板看起来像这样
div(ng-repeat='project in projectCtrl.projects')
p(style='margin-bottom:0px') {{project.title}}
span.italic {{project.start_date | date}} - {{project.end_date | date}}
p {{project.abstract}}
a.btn-xs(style='color:black' ng-click='projectCtrl.toggleProjectDetails(project)')
i.fa.fa-angle-double-down
p(ng-show='{{project.showDetails}}') {{project.details}}
项目看起来像这样:
[{
"title" : "Project Title",
"abstract" : "Short abstract to show what you've done",
"details" : "Lorem impusm bla bla bla",
"start_date" : ISODate("2014-07-02T11:07:34.000Z"),
"end_date" : ISODate("2014-07-02T11:07:34.000Z"),
"links" : [
{
"title" : "link name",
"url" : "www.google.com"
}
]
},...]
我的问题是,当我调用toggleProjectDetails
时,函数被执行,但页面的相应部分不会再次渲染。就像ng-show
没有被重新执行一样。
我在这里缺少什么?
这是plunker link。
答案 0 :(得分:0)
最后使用你的plunker进行了大量的调试后得到了它。最后开始在toggle方法中更改project.details,该方法有效。然后找到了ng-show bug。
ng-show不应该有{{}}。而不是
p(ng-show='{{project.showDetails}}') {{project.details}}
使用
p(ng-show='project.showDetails') {{project.details}}
并完成。
答案 1 :(得分:0)
我设法解决了我的问题,简而言之,我为数组创建了一个控制器,它处理了服务,并为数组中的每个元素添加了一个控制器。我的代码如下所示:
Controller和保存项目的指令(我的数组从服务器返回):
app.directive('projects', ['projectServices',
function(projectServices) {
var projectController = function($scope) {
projectServices.getProjects()
.success(function(result) {
$scope.projects = result.data
})
.error(function(err) {
console.log('error ' + err)
})
}
return {
restrict: 'E',
templateUrl: '/partials/project',
controller: projectController,
controllerAs: 'ProjectListController'
}
}
])
每个项目的控制器:
app.controller("projectController", ["$scope",
function($scope) {
$scope.project.shDetails = false;
$scope.toggleDetails = function() {
$scope.project.shDetails = !$scope.project.shDetails
};
$scope.showDetails = function() {
return $scope.project.shDetails
}
}
])
和我修改过的模板:
div(ng-controller="projectController" ng-repeat='project in projects')
p(style='margin-bottom:0px') {{project.title}}
span.italic {{project.start_date | date}} - {{project.end_date | date}}
p {{project.abstract}}
a.btn(style='color:black' ng-click='toggleDetails()')
i.fa.fa-angle-double-down
p(ng-show='showDetails()') {{project.details}}