我们正在 angularjs 1.2 中开发一组(理想情况下)灵活的、基于组件的可重用模板,以开发一系列电子学习模块。
规范的一部分要求跟踪“可完成的”组件。目前主 Controller 如下所示:
app.controller('mainCtrl', ['$scope', function($scope) {
$scope.completables = [];
$scope.completed = [];
$scope.addCompletable = function (object) {
$scope.completables.push(object);
// also set correlating completed property to 'false' for each completable added
$scope.completed.push(false);
}
$scope.componentCompleted = function(id) {
// Set complete to 'true' for matching Sscope.completed array index
// We COULD use .indexOf on the completables array, but that doesn't work with IE8
var tempArray = $scope.completables;
var matchingIndex = -1;
for (var i=0; i<tempArray.length; i++) {
if (tempArray[i]==id) {
matchingIndex = i;
}
}
if (i>-1) {
$scope.completed[matchingIndex] = true;
}
}
}]);
我们有一个 eng-completable 属性,可以触发以下指令:
app.directive('engCompletable', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
// add the id of this element to the completables array in the main controller
scope.$parent.addCompletable(attrs.id);
}
}
});
因此,每次 Angular 遇到元素上的“eng-completable”属性时,它都会在父范围上调用 addCompletable,将元素 id 添加到“completables”数组中,并将“false”添加到“completed”的相应索引中数组。
在 eng-popup 属性指令中,我们有一个函数来检查它是否已变得可见:
app.directive('engPopup', function() {
return {
restrict: 'A',
replace: true,
templateUrl: 'components/popup.html',
link: function(scope, element, attrs) {
scope.$watch(function() { return element.is(':visible') }, function() {
scope.$parent.componentCompleted(attrs.id);
});
}
};
});
它还使用父作用域来触发“componentCompleted”函数。有人告诉我,引用父作用域是一种不好的做法,而且显然它也会扰乱我们的单元测试。
我想知道有什么替代方案。如何让我的应用程序知道特定组件已完成?应该在哪里跟踪这个状态?
我真的很想知道如何做到这一点 - 而不仅仅是被告知我做错了。请让我知道替代方案是什么。
但是,一如既往,我们将不胜感激任何帮助。
最佳答案
一种替代方法是创建一个服务来负责跟踪所有组件并保持其状态(完成/未完成)。
它将消除对
:)
关于javascript - 如何避免在 Angular 1.2 中使用 'scope.$parent...',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39292730/