相关疑难解决方法(0)

如何从AngularJS中具有自己的范围*的自定义指令*中访问父作用域?

我正在寻找任何方式访问指令中的"父"范围.范围,转换,要求的任何组合,从上面传递变量(或范围本身)等.我完全愿意向后弯腰,但我想避免一些完全hacky或不可维护的东西.例如,我知道我现在可以通过$scope从preLink参数中获取并迭代它的$sibling范围来找到概念性的"父".

我真正想要的是能够$watch在父范围内表达.如果我能做到这一点,那么我可以完成我在这里要做的事情: AngularJS - 如何使用变量渲染部分?

重要的一点是,该指令必须可以在同一父范围内重复使用.因此默认行为(范围:false)对我不起作用.我需要每个指令实例的单独范围,然后我需要$watch一个存在于父范围内的变量.

代码示例值1000个单词,因此:

app.directive('watchingMyParentScope', function() {
    return {
        require: /* ? */,
        scope: /* ? */,
        transclude: /* ? */,
        controller: /* ? */,
        compile: function(el,attr,trans) {
            // Can I get the $parent from the transclusion function somehow?
            return {
                pre: function($s, $e, $a, parentControl) {
                    // Can I get the $parent from the parent controller?
                    // By setting this.$scope = $scope from within that controller?

                    // …
Run Code Online (Sandbox Code Playgroud)

angularjs angularjs-directive

323
推荐指数
4
解决办法
26万
查看次数

在Transcluded Directive中访问父范围

我想访问父指令的范围,但我似乎无法获得正确的设置组合.这是可能的,这是正确的方法吗?

我真的想避免在MyCtrl中放置类似SOME_CONST(这可以帮助我通过控制流程进行DOM更新)

<div ng-controller="MyCtrl">
    <parent>
        <child></child>
    </parent>
</div>

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.obj = {prop:'foo'};
}

myApp.directive('parent', function() {
    return {
        scope: true,
        transclude: true,
        restrict: 'EA',
        template: '<div ng-transclude><h1>I\'m parent {{obj.prop}}<h1></div>',
        link: function(scope, elem, attrs) {
            scope.SOME_CONST = 'someConst';
        }
    }
});

myApp.directive('child', function() {
    return {
        restrict: 'EA',
        template: '<h1>I\'m child.... I want to access my parent\'s stuff, but I can\'t.  I can access MyCtrlScope though, see <b>{{obj.prop}}</b></h1> how can I access the <b>SOME_CONST</b> value …
Run Code Online (Sandbox Code Playgroud)

angularjs angularjs-directive angularjs-scope

29
推荐指数
3
解决办法
3万
查看次数