使用$scope隔离作用域功能.美元的新产业



我想弄清楚是否有可能获得属性绑定的自动功能,您可以从隔离作用域获得:

scope : { someAttr: '@' }

同时保留scope.$new():

的透明作用域——>parentScope属性访问权限
$scope.foo = 'foo';
$scope.bar = 'bar';
var childScope = $scope.new();
childScope.foo = 'childFoo';
// childScope == { foo: 'childFoo', bar: 'bar' }

想法?我不知道如何在控制器中创建一个新的作用域,然后从指令发送属性到…???

要清楚,我最终想在一个控制器:

$scope === {
           attr : << attribute from directive instance >>
    , parentKey : << transparent to parent diretive's scope >>
}

你自己做其实很简单。您使用$parse服务将表达式转换为函数,然后只需在作用域上公开该函数。

当Angular在指令代码中遇到&作用域时,它会在内部做这样的处理:https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L892-L898

所以你可以编写一个小的辅助函数,它可以在你想要的属性上为你完成这三行代码。

/*
 * Creates a child scope, turning the property names in the whatToGetter
 * array into getters
 * @param parentScope scope to inherit
 * @param whatToGetter array of string properties to turn into getters 
 *                     of the parent on the child scope
 * @returns scope new child scope
 */
function childScope(parentScope, whatToGetter) {
  var child = parentScope.$new();
  angular.forEach(whatToGetter, function(property) {
    var getter = $parse(parentScope[property]);
    child[property] = function() {
      return getter(parentScope);
    };
  });
  return child;
}
var scope = {foo: '1', bar: '2'};
var child = childScope(scope, ['bar']);
console.log(child.foo); // --> 1
console.log(child.bar()); // --> 2

最新更新