我使用下面的指令(仅添加相关代码),它在公共服务属性中设置对象并加载另一个部分视图。从第二页面控制器,需要检索先前设置的对象并在UI中显示。问题是,即使console.log()
给出预期值,也不会在UI中显示数据。这与执行顺序有关吗?
指令:
movieBank.directive('movieSummary', function(commonServices){
return{
restrict : 'E',
template : '<input type="button" value="Detail" class="btn btn-primary button" ng-click="go();">',
scope : {
movie : '@'
},
link: function(scope, elem, attrs){
scope.go = function(){
console.log('clicked ' +scope.movie); // gives correct values
commonServices.setMovie(scope.movie);
commonServices.changeLocation('/movieDetail');
};
}
}
});
第二页conotroller:
movieBank.controller('movieDetailController', function($scope, commonServices){
$scope.movie = commonServices.getMovie();
console.log('got ' + $scope.movie); // gives correct values
});
服务:
movieBank.service('commonServices', function(){
var movies = [];
var movie = {};
return {
getMovie : function () {
return movie;
},
setMovie : function(m){
movie = m;
}
};
});
Page:
<header class="panel-heading">
<span class="title">{{movie.Title}}</span>
<div star-rating rating-value="movie.Rating"></div>
</header>
<p class="panel-body">
{{movie.Description}}
</p>
<div class="panel-body">
Directed By : {{movie.Director}}</br>
Release Year : {{movie.ReleaseYear}}</br>
Language : {{movie.Language}}
</div>
答案 0 :(得分:0)
通过将控制器功能传递到隔离范围,找到替代解决方案,如下所示。分享这个,以便其他人也能获得好处。
修改指令以接受函数(而不是模板ng-click和scope的更改)
movieBank.directive('movieSummary', function(){
return{
restrict : 'E',
template : <input type="button" value="Detail" class="btn btn-primary button" ng-click="details({m : movie});">',
scope : {
details : '&'
}
}
});
使用指令
时传递控制器功能<movie_Summary details="goToMovieDetail(movie)"></movieSummary>
使用指令的控制器
movieBank.controller('movieListController', function($scope, commonServices){
$scope.goToAddMovie = function(){
commonServices.changeLocation('/add');
}
$scope.goToMovieDetail = function(movie){
commonServices.setMovie(movie);
commonServices.changeLocation('/movieDetail');
}
});