show input = {{showInp-6ren">
gpt4 book ai didi

angularjs - $scope var 不在 child 中传播

转载 作者:行者123 更新时间:2023-12-03 10:31:54 24 4
gpt4 key购买 nike

在项目列表中,单击一个项目会使用 ng-show="showInput=true" 打开一个输入字段。

 <div ng-app="myApp" ng-controller="Ctrl">
<li ng-click="showInput=true" ng-repeat="label in labels">{{label}} - ---> show input = {{showInput}}
<form ng-show="showInput" >
<input type=text value={{label}}><button ng-click="saveDate()">save</button>
</form>
</li>
</div>

但是,当点击保存时,设置showInput=false 表单不会隐藏:

 angular.module('myApp', [])
.controller('Ctrl', ['$scope', function($scope) {
$scope.labels=["click a", "click b", "click c", "click d", "click e"];
$scope.showInput = false;

$scope.saveData = function(){
$scope.showInput = false;
}
}]);

我怀疑这是父/子作用域问题。谁能指出如何进行这项工作?

fiddle :http://jsfiddle.net/supercobra/PUZzZ/

最佳答案

这里有一些错误。

  1. 在您的 HTML 中,您应该编写 saveData()(而不是 saveDate())。

  2. 当您点击 li 中的任何元素(包括您的按钮)时,它会将您的 showInput 设置为 true。

  3. 您正在处理范围内的纯 JavaScript 对象。在 AngularJS Meetup you can see here 有一个问题专门询问如何处理这个问题.最好的解决方案似乎是使用一个对象,以便子对象和父对象使用相同的引用对象。这是我的做法(使用 key 系统而不是标签会更安全)

Look at this fiddle for my solution.

<div ng-app="myApp" ng-controller="Ctrl">
<li ng-repeat="label in labels">
<span ng-click="showInput[label] = true">{{label}}</span> - ---> show input = {{showInput}}
<form ng-show="showInput[label]" >
<input type=text value={{label}}><button ng-click="saveData(label)">save</button>
</form>
</li>
</div>


angular.module('myApp', [])
.controller('Ctrl', ['$scope', function($scope) {
$scope.labels=["click a", "click b", "click c", "click d", "click e"];
$scope.showInput = {};

$scope.saveData = function(label){
$scope.showInput[label] = false;
}
}]);

这很完美。问题是如果您在子项中使用 $scope 变量,则在您保存时父项将无法访问它。

关于angularjs - $scope var 不在 child 中传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18463645/

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