Javascript 我被抽走了
我有两个相互完全分离的指令(参见标记): 在albums指令中,这是:Javascript 我被抽走了,javascript,angularjs,scope,Javascript,Angularjs,Scope,我有两个相互完全分离的指令(参见标记): 在albums指令中,这是: app.directive('albums', function(AlbumService) { function controller($scope) { $scope.data = []; $scope.fn = { getAlbums: function() { // AlbumService stuff }, // bunch of fu
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
对象中,这很好,但是在某些事件处理中,当我访问users
指令中的fn
对象时,我会从albums
指令中得到另一个。尽管如此,如果我在controller
函数中定义了console.log,我会得到正确的对象。请参见一个示例:
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
让我头疼
有什么想法吗?谢谢。在创建指令以提供隔离作用域时定义
作用域:true
。@tymeJV是的,就是这样,谢谢。
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'
}
});
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'
}
});