От чтения Scopes (Part 2 of the AngularJS - from beginner to expert in 7 steps series): A $scope
может содержать как данные, так и функции, доступные в представлении. Если AngularJS не может найти функцию на локальном $scope
, то содержащее (родительское) $scope
будет проверено на предмет свойства или метода.Почему размер объекта родительского контроллера недоступен из (дочерней) директивы?
Учитывая мою реализацию функции компилировать директивы (на основе Angularjs: understanding a recursive directive):
compile: function(tElement, tAttrs) {
var contents = tElement.contents().remove();
console.log(contents);
var compiledContents;
// postLink function.
return {
post: function(scope, iElement, iAttrs) {
if (!compiledContents) {
// Get linking function.
compiledContents = $compile(contents);
}
// Link scope and the template together.
compiledContents(scope, function(clone) {
iElement.append(clone);
});
scope.myEvent = function() {
console.log("My Event handled!");
};
},
pre: function(scope, iElement, iAttrs) { }
}
}
В приведенном выше коде, я приложил функцию к $scope
от экземпляра элемента, и это успешно называется с точки зрения. Тем не менее, я ожидал, чтобы иметь возможность переместить определение функции из экземпляра элемента сферы и в родительском диспетчерском $scope
:
angular.module('Myapp').controller('MyParentController', ['$scope',
function($scope) {
$scope.myEvent = function() {
console.log("My Event handled!");
};
}]);
Однако функция родительского контроллера никогда не вызываются, даже если он является родителем директивы для который я предоставил для себя самостоятельно.
Обновлено добавить код для директивы:
angular.module('Myapp').directive("my-directive", function(RecursionHelper) {
return {
restrict: "E",
scope: {
data: '=data'
},
templateUrl: 'view.html',
compile: function(tElement, tAttributes) {
return RecursionHelper.compile(tElement, tAttributes);
}
};
});
ого RecursionHelper:
angular.module('Myapp').factory('RecursionHelper',
['$compile',
function($compile) {
var RecursionHelper = {
compile: function(tElement, tAttrs) {
var contents = tElement.contents().remove();
var compiledContents;
return {
post: function(scope, iElement, iAttrs) {
if (!compiledContents) {
compiledContents = $compile(contents);
}
compiledContents(scope, function(clone) {
iElement.append(clone);
});
},
pre: function(scope, iElement, iAttrs) { }
}
}
}
return RecursionHelper;
}]);
вы можете предоставить полный код директивы – harishr
@HarishR - OP обновлен, чтобы включить полный директивный код. – Jack
называется '$ scope.myEvent' через' ng-click'? не могли бы вы также вставить шаблон своей директивы здесь – elaijuh