将全局作用域变量绑定到指令局部变量



我很难理解控制器和指令之间的作用域链接。

我想做的(这应该能帮助我学到很多)是将控制器中的$scope.systems绑定到指令中的data

所以我设置了一个简单的指令调用:

<combobox data="systems"></combobox>

我也尝试绑定变量,但对我来说没有意义

<combobox data="{{systems}}"></combobox>

然后我创建了这样的驱动程序

.directive('combobox', function ($timeout) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: '/angular/directives/combobox.php',
        link: function (scope, element, attrs) {
            console.log(attrs.data);
            $timeout(function () {
                console.log(scope.systems);
                console.log($scope[attrs.data]);
            }, 1000);
        }
    }
});

我考虑在指令返回中添加一个作用域参数

scope: {
    'systems': '='
}

scope: {
    'systems': '=data'
}

我已经能够设置简单的指令,其中值被绑定到指令范围,并且它们已经起作用了。现在我正试图创建一个可重复使用的指令,在那里我可以告诉它要使用来自控制器范围的哪些数据,但我只是陷入了困境。

这应该可以工作。虽然我不确定为什么你的模板是php文件。。。

<combobox data="foo"></combobox>
<combobox data="bar"></combobox>
app.directive('combobox', function ($timeout) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            //this will set $scope.systems
            //with the value gotten from evaluating what is in
            //the data attribute
            'systems': '=data'
        },
        templateUrl: '/angular/directives/combobox.php',
        link: function (scope, element, attrs) {
            console.log(scope.systems);
        }
    }
});

顺便说一句,不要使用replace。Angular团队表示,它可能很快就会消失,因为它引发了太多问题,而且根本没有必要。

最新更新