我有两个指令彼此完全分开(参见标记):
<div class="col-xs-12">
<users></users>
</div>
<div class="col-xs-12">
<albums></albums>
</div>
在用户指令中,我有类似的内容:
app.directive('users', function(UserService) {
function controller($scope) {
$scope.data = [];
$scope.fn = {
getUsers: function() {
// UserService stuff
},
// bunch of functions here
}
}
return {
restrict: 'E',
controller: controller,
templateUrl: 'users.html'
}
});
在专辑指令中,这个:
app.directive('albums', function(AlbumService) {
function controller($scope) {
$scope.data = [];
$scope.fn = {
getAlbums: function() {
// AlbumService stuff
},
// bunch of functions here
}
}
return {
restrict: 'E',
controller: controller,
templateUrl: 'albums.html'
}
});
我喜欢将我的函数放在$scope.fn
对象中,这很好,但是当我在某些事件处理中访问fn
指令中的users
对象时,我得到了另一个albums
指令。虽然,如果我console.log
在controller
函数中定义它之后,我就会得到正确的对象。查看示例:
app.directive('users', function(UserService) {
function controller($scope) {
$scope.data = [];
$scope.fn = {
getUsers: function() {
// UserService stuff
},
// bunch of functions here
}
$scope.someClickEvent = function() {
console.log($scope.fn) /* Gives me the wrong object */
$scope.fn.getUsers() /* is undefined */
$scope.fn.getAlbums() /* executes just fine */
}
console.log($scope.fn) /* Gives me the right object */
}
return {
restrict: 'E',
controller: controller,
templateUrl: 'users.html'
}
});
另请注意,$scope.data
对两个指令都没有问题,只有$scope.fn
让我头疼。
有关于此的任何想法吗?谢谢。