gpt4 book ai didi

javascript - 将 Angular 范围变量的字符串描述传递给指令

转载 作者:行者123 更新时间:2023-11-28 18:40:31 25 4
gpt4 key购买 nike

我正在尝试将动态变量传递给 Angular Directive(指令)。我可以用一个字符串来描述我所追求的变量。但我无法将该字符串绑定(bind)到实际的 Angular 范围变量。

my_app.js:

(function() {
var app = angular.module("my_app");
app.controller("MyController", [ "$scope", function($scope) {
$scope.my_data = {
name: "bob",
display_detail: false,
children: [
{
name: "fred",
display_detail: false
},
{
name: "joe",
display_detail: true
}
]
}

app.directive('myDirective', ['$http', function($http) {
return {
restrict: "EAC",
link: function (scope, element, attrs) {
var model = attrs["modelToWatch"];
var watched_name = model + ".display_detail";
scope.$watch(watched_name, function (is_displayed) {
if (is_displayed) {
// do something clever w/ $http...
}
}
}
}
}]);

my_template.html:

<div ng-app="my_app">
<div ng-controller="MyController">
<my_directive model_to_watch="my_data.children[1]"/>
</div>
</div>

这个想法是将字符串“my_data.children[1]”传递给指令。我的目标是以某种方式评估这一点并最终得到实际模型(上面名为“joe”的模型)。

最佳答案

为什么不直接将其传递到指令的范围内?

app.directive('myDirective', ['$http', function($http) {
return {
scope: {
watchedName: '='
},
restrict: "EAC",
link: function (scope, element, attrs) {
scope.$watch(scope.watchedName.display_detail, function (is_displayed) {
if (is_displayed) {
// do something clever w/ $http...
}
}
}
}

<my-directive watched-name="my_data.children[1]"/>

关于javascript - 将 Angular 范围变量的字符串描述传递给指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36189064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com