Ответ 1
Эта директива обеспечивает двухстороннюю привязку данных между родительской областью и переименованными "локальными" переменными в область дочерних объектов. Он может быть объединен с другими директивами типа ng-include
для многократного повторного использования шаблона. Требуется AngularJS 1.2.x
jsFiddle: AngularJS - включить частичное с локальными переменными
Разметка
<div with-locals locals-cars="allCars | onlyNew"></div>
Что происходит:
- Это в основном расширение директивы
ngInclude
, позволяющее передавать переменные переименованные из родительской области.ngInclude
НЕ требуется вообще, но эта директива была разработана для того, чтобы хорошо работать с ней. - Вы можете прикрепить любое количество атрибутов
locals-*
, которые будут проанализированы и просмотрены для вас как Angular выражения.- Эти выражения становятся доступными включенным частичным, прикрепленным как свойства объекта
$scope.locals
. - В приведенном выше примере
locals-cars="..."
определяет выражение, которое становится доступным как$scope.locals.cars
. - Подобно тому, как атрибут
data-cars="..."
будет доступен через jQuery с помощью.data().cars
- Эти выражения становятся доступными включенным частичным, прикрепленным как свойства объекта
Директива
EDIT Я рефакторизую использовать (и не зависимо от) директиву ngInclude
и переместить некоторые вычисления в функцию компиляции для повышения эффективности.
angular.module('withLocals', [])
.directive('withLocals', function($parse) {
return {
scope: true,
compile: function(element, attributes, transclusion) {
// for each attribute that matches locals-* (camelcased to locals[A-Z0-9]),
// capture the "key" intended for the local variable so that we can later
// map it into $scope.locals (in the linking function below)
var mapLocalsToParentExp = {};
for (attr in attributes) {
if (attributes.hasOwnProperty(attr) && /^locals[A-Z0-9]/.test(attr)) {
var localKey = attr.slice(6);
localKey = localKey[0].toLowerCase() + localKey.slice(1);
mapLocalsToParentExp[localKey] = attributes[attr];
}
}
var updateParentValueFunction = function($scope, localKey) {
// Find the $parent scope that initialized this directive.
// Important in cases where controllers have caused this $scope to be deeply nested inside the original parent
var $parent = $scope.$parent;
while (!$parent.hasOwnProperty(mapLocalsToParentExp[localKey])) {
$parent = $parent.$parent;
}
return function(newValue) {
$parse(mapLocalsToParentExp[localKey]).assign($parent, newValue);
}
};
return {
pre: function($scope, $element, $attributes) {
// setup `$scope.locals` hash so that we can map expressions
// from the parent scope into it.
$scope.locals = {};
for (localKey in mapLocalsToParentExp) {
// For each local key, $watch the provided expression and update
// the $scope.locals hash (i.e. attribute `locals-cars` has key
// `cars` and the $watch()ed value maps to `$scope.locals.cars`)
$scope.$watch(
mapLocalsToParentExp[localKey],
function(localKey) {
return function(newValue, oldValue) {
$scope.locals[localKey] = newValue;
};
}(localKey),
true
);
// Also watch the local value and propagate any changes
// back up to the parent scope.
var parsedGetter = $parse(mapLocalsToParentExp[localKey]);
if (parsedGetter.assign) {
$scope.$watch('locals.'+localKey, updateParentValueFunction($scope, localKey));
}
}
}
};
}
};
});