【问题标题】:Why isolate scope "@" and $apply don't work as expected为什么隔离范围“@”和 $apply 不能按预期工作
【发布时间】:2013-11-18 03:57:56
【问题描述】:

我一直在研究 AngularJS,特别是看了视频:

http://www.thinkster.io/pick/IgQdYAAt9V/angularjs-directives-talking-to-controllers

本视频展示了一个指令与控制器对话的示例,我对其进行了一些修改,以尝试了解是否也可以使用隔离范围来获得类似的结果。考虑一个 HTML sn-p,例如:

<div enter="loadMoreTweets()">Roll Over This</div>

还有一个 Angular 控制器和指令定义为:

app.controller('scopeCtrl', function($scope) {
    $scope.loadMoreTweets = function () {
        alert("loading more tweets");
    }
}).directive('enter', function() {
    return {
        restrict: "A",
        scope: {enter: "@"},
        link: function(scope, element, attrs) {
            element.bind("mouseenter", function() {
                //scope.$apply(attrs.enter);
                scope.$apply(scope.enter);
            })
        }
    }
});

在 DIV 上滚动不会导致错误并且没有任何效果。

如果我注释掉隔离范围并使用 element.bind() 中的注释行而不是对 scope.enter 的引用,则滚动 DIV 会导致 alert() 按预期显示。

问题:如果“@”隔离作用域在属性值和作用域属性之间创建了单向绑定,那么我会预料到scope.enter == attrs.enter。显然这不是真的。为什么?

【问题讨论】:

    标签: angularjs-directive angularjs-scope angularjs-controller


    【解决方案1】:

    原因是“@”是一种单向数据绑定,但它始终作为string 传递

    scope: {              // set up directive's isolated scope
      name: "@",          // name var passed by value (string, one-way)
      age: "=",           // age var passed by reference (two-way)
      showName: "&"       // passed as function
    }
    

    at 符号“@”表示该变量是按值传递的。该指令接收一个字符串,其中包含从父范围传入的值。该指令可以使用它,但它不能更改父作用域中的值(它是孤立的)。

    【讨论】:

    • 谢谢。我确实理解,但这就是为什么这种行为让我感到惊讶。在标记中 enter="loadMoreTweets()" 指定了一个字符串,至少它看起来像一个字符串,因为它用引号引起来。所以隔离范围应该,我想选择相同的字符串,所以隔离范围的属性“enter”将具有字符串值“loadMoreTweets()”。在我看来,这与字符串 attrs.enter 相同,后者还将包含标记中指定的字符串。似乎两者都是字符串并且都具有相同的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 2011-04-22
    • 2021-05-30
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多