所以我有这个指令,它有自己的作用域,但我想访问其父 Controller 中的函数。如果父 Controller 使用 $scope.getElementsList() 公开函数,我可以这样做,尽管我试图避免使用 $scope 并且我使用 self.getElementsList() 公开函数并且指令无法访问它.
指令:
angular.module('myApp').directive('accountBalance', function() {
return {
scope: {
elementId: '=elementid'
},
transclude: true,
restrict: 'E',
templateUrl: '../views_directives/account-balance.html',
controller: function($scope) {
$scope.removeElement = function(){
//this where I want to access the parent function
console.log($scope.$parent.getElementsList());
console.log("ALSO I WANT TO ACCESS THIS DIRECTIVE elementId WITHOUT USING $scope", $scope.elementId);
}
}
};
});
父 Controller :
angular.module('myApp').controller('AppDesignCtrl', function ($scope) {
var self = this;
self.elementsList = [];
self.getElementsList = function(){
return self.elementsList;
}
});
我还想知道在指令 Controller 内部访问传递给指令的 $scope 的数据的最佳方式是什么。
scope: {
elementId: '=elementid'
},
更新
<div>
<i class="fa fa-arrows element-drag"></i>
<i class="fa fa-trash-o element-remove" ng-click="removeElement()"></i>
</div>
那么从指令 Controller 内部的指令模板调用函数呢?我需要用 $scope.removeElement() 之类的东西来公开它们吗?我如何使用 this.removeElement() 并能够从模板访问它?
抱歉这个问题太长了。自从我离开 Angular 一年多以来,我正在尝试为我的新项目设置最佳实践。
提前致谢
最佳答案
(从下往上...)
要调用 Controller 中的函数而不使用 Angular >= 1.2 中的作用域,请使用 controllerAs
语法:
<div ng-controller="AppDesignCtrl as appDesignCtrl">
...
<i class="fa fa-trash-o element-remove" ng-click="appDesignCtrl.removeElement()"></i>
</div>
并且removeElement()
必须是 Controller 的一个方法:
angular.module('myApp').controller('AppDesignCtrl', function ($scope) {
...
this.removeElement = function() {
...
};
});
要从 Angular >= 1.3 中的 Controller 访问范围数据,请使用新的 bindToController: true
配置(这在与新的 controllerAs
语法结合时特别有用):
angular.module('myApp').directive('accountBalance', function() {
return {
...
scope: {
elementId: '=elementid'
},
controller: function() {
// now elementId is a member of the controller:
console.log(this.elementId);
}
};
});
说了这些,关于如何从指令调用 getElementsList
的答案是:
angular.module('myApp').directive('accountBalance', function() {
return {
...
scope: {
elementId: '=elementid',
getElementList: '&'
},
controller: function() {
...
// invoking the expression that was passed to us
var theElements = this.getElementList();
}
};
});
正确的表达式应该传递为:
<div ng-controller="AppDesignCtrl as appDesignCtrl">
<account-balance element-id="xxx"
get-elements-list="appDesignCtrl.getElementsList()"></account-balance>
</div>
关于javascript - 在没有 $scope 的情况下指令访问父 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29516537/