将AngularJS范围变量从指令传递到控制器的最简单方法?


Answers:


150

于2014/8/25编辑: 是我分叉的地方。

谢谢@anvarik。

这是JSFiddle。我忘记了我在哪里分叉。但这是一个很好的示例,向您展示了=和@之间的区别

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

29
很好的解释和例子!我不知道为什么文档如此复杂?...或者我不是那么出色的程序员?
kshep92 2013年

2
请注意,该提琴的工作方式与之相同,但是如果将角度版本更改为较新的版本(即从1.0.1到1.2.1),它将不再起作用。语法必须有所更改。
eremzeit 2014年

2
最后,一个明确的例子很有意义。2小时头痛症状在10秒内解决。
克里斯

4
在方法说明如何将值从控制器传递给指令而不是从指令传递给控制器​​时,大家如何投票赞成这个答案?
Tiberiu C.

2
isolatedBindingFoo:'= bindingFoo'可以将指令中的数据传递给控制器​​。或者您可以使用服务。在您否决某人之前,如果您不理解,欢迎您首先询问。
maxisam 2015年

70

等到angular对变量进行求值

我对此有很多摆弄,即使使用"="范围中定义的变量也无法使其正常工作。这是三种解决方案,具体取决于您的情况。


解决方案1


我发现将变量传递给指令时,尚未对其进行角度求值。这意味着您可以访问它并在模板中使用它,但不能在链接或应用程序控制器函数中使用它,除非我们等待对其进行评估。

如果您的变量正在更改或通过请求获取,则应使用$observe$watch

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    console.log(value);
                    // pass value to app controller
                    scope.variable = value;
                }
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        console.log(value);
                        // pass value to app controller
                        $scope.variable = value;
                    }
                });
            }
        ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

这是html(请记住方括号!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

请注意"=",如果正在使用该$observe函数,则不要在范围内将变量设置为。此外,我发现它以字符串形式传递对象,因此,如果要传递对象,请使用解决方案#2scope.$watch(attrs.yourDirective, fn)(如果变量未更改,则使用解决方案#3)。


解决方案#2


如果您的变量是在例如另一个控制器中创建的,但是只需要等到angular对它进行评估,然后再将其发送到应用控制器,我们就可以使用它$timeout,直到$apply它运行为止。另外,我们还需要使用$emit它来将其发送到父作用域应用控制器(由于伪指令中的隔离作用域):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        },
        link: function (scope, element, attrs) {
            // wait until after $apply
            $timeout(function(){
                console.log(scope.yourDirective);
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
            $timeout(function(){
                console.log($scope.yourDirective);
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
            });
        }]
    };
}])
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        console.log(value);
        $scope.variable = value;
    });
}]);

这是html(无括号!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

解决方案#3


如果您的变量没有变化,并且您需要在指令中对其进行求值,则可以使用以下$eval函数:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);
            console.log(scope.variable);

        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
                console.log($scope.variable);
            }
         ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

这是html(请记住方括号!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

另外,看看这个答案:https : //stackoverflow.com/a/12372494/1008519

FOUC(未样式化内容的闪烁)问题的参考:http ://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

对于感兴趣的人:这是关于角寿命周期的文章


1
有时ng-if="someObject.someVariable",对指令(或将指令作为属性的元素)进行简单处理就足够了-指令仅在someObject.someVariable定义后才插入。
marapet
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.