将全局范围变量绑定到指令局部变量
Binding global scope variable to directive local variable
我无法理解控制器和指令之间的作用域链接。
我正在尝试做的(这应该可以帮助我学到很多东西)是将我的控制器中的 $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);
}
}
});
我考虑过在指令中添加范围参数 return
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 团队表示它可能很快就会消失,因为它引起了太多问题,而且无论如何都没有必要。
我无法理解控制器和指令之间的作用域链接。
我正在尝试做的(这应该可以帮助我学到很多东西)是将我的控制器中的 $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);
}
}
});
我考虑过在指令中添加范围参数 return
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 团队表示它可能很快就会消失,因为它引起了太多问题,而且无论如何都没有必要。