gpt4 book ai didi

javascript - 初始化 Angular Directive(指令)中的文本输入字段

转载 作者:行者123 更新时间:2023-11-28 06:55:02 24 4
gpt4 key购买 nike

我有一个显示输入字段的指令,我想用来自服务器的数据初始化这些字段。问题是我在使用 ng-model 时无法做到这一点。在使用指令之前,我在 Controller 中使用了类似 $scope.field1 = $scope.first.field1

这是我的代码。为了便于阅读,我对其进行了简化,但想法就在这里。

在我的 Controller 中,我有以下代码:

app.controller('MyController',
['$scope', 'myData', function($scope, myData) {
myData.then(function(data) {
$scope.first = data.first;
$scope.second = data.second;
});
}]);

在第一个和第二个内部,我有 2 个字段:field1 和 field2。

在 html 代码中,我有这样的内容:

<h1>First</h1>
<my-directive info="first"></my-directive>
<h1>Second</h1>
<my-directive info="second"></my-directive>

该指令如下:

app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
info: '='
},
templateUrl: 'static/js/myDirective.html',
link: function(scope, element, attrs) {
scope.doStuff = function() {
/* Do stuff with
scope.field1 and scope.field2 */
}
}
};
});

和 myDirective.html 代码:

<input type="text" ng-model="myfield1" />
<input type="text" ng-model="myfield2" />
<input type="submit" ng-click="doStuff()" />

如果在 myDirective.html 中我写:

<input type="text" value="info.field1" />

我可以很好地看到该值。

有什么想法吗?

最佳答案

您的指令可能会在数据加载之前初始化。并且您的指令将 ng-model 视为 undefined variable 。您没有直接在模板中使用信息,因此没有适合您的自动 $watch :)。

你需要$watch指令中的info变量并在变化时调用你的doStuff函数。

注意:我不建议仅为此任务向指令添加 Controller 。当您需要与其他指令通信时,需要向指令添加 Controller 。不用于等待异步数据

编辑

你应该这样做

app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
info: '='
},
templateUrl: 'static/js/myDirective.html',
link: function(scope, element, attrs) {
scope.doStuff = function() {
/* Do stuff with
scope.field1 and scope.field2 */
}
scope.$watch('info', function(newValue){
scope.doStuff();
});
}
};
});

关于javascript - 初始化 Angular Directive(指令)中的文本输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32632006/

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