Angularjs模型数组不使用模板更新
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Angularjs模型数组不使用模板更新相关的知识,希望对你有一定的参考价值。
我用以下代码创建了模板。编辑功能正常,但模型正在更新。
在模板中,我用ng-model
绑定了模型,但仍然没有在编辑时更新模型hobbies
有任何想法吗?
<html>
<head>
<title>
Angular Edit Template
</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" integrity="sha384-PmY9l28YgO4JwMKbTvgaS7XNZJ30MK9FAZjjzXtlqyZCqBY6X6bXIkM++IkyinN+" crossorigin="anonymous">
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.7/angular.js"></script><!-- Latest compiled and minified CSS -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js" integrity="sha384-vhJnz1OVIdLktyixHY4Uk3OHEwdQqPppqYR8+5mjsauETgLOcEynD9oPHhhz18Nw" crossorigin="anonymous"></script>
<script type="text/javascript">
angular.module('myApp', [])
.controller('myCtrl', function($scope){
$scope.hobbies = ["Swimming", "Reading"]
})
.directive('component', function(){
return {
template: [
'<div>',
'<span ng-show="!editing">{{ value }} <i ng-click="editing = true" class="glyphicon glyphicon-pencil"></i></span>',
'<span ng-show="editing"><input type="input" ng-model="value"><i ng-click="editing = false" class="glyphicon glyphicon-ok"></i></span>',
'</div>'
].join(''),
restrict: 'E',
scope: {
value: '=value'
},
link: function($scope){
$scope.editing = false;
}
}
});
</script>
</head>
<body>
<div id="test" ng-app="myApp" ng-controller="myCtrl">
<ul ng-repeat="n in hobbies">
<li>
<component value="n"></component>
</li>
</ul>
<span>{{ hobbies }}</span>
</div>
</body>
</html>
答案
看看这个,问题是你是双向绑定一个字符串,而不是一个对象,这意味着你实际上没有得到好处:If you are not using a .(dot) in your AngularJS models you are doing it wrong?
如果你在父母中使用一个对象,要么传递值,要么传递整个对象,你会发现它的效果更好一些。
$scope.hobbies = [{id:1,name:"Swimming"},{id:2,name:"Reading"}]
然后
<ul ng-repeat="n in hobbies">
<li>
<component value="n.name"></component>
</li>
</ul>
要么
'<span ng-show="!editing">{{ value.name }} <i ng-click="editing = true" class="glyphicon glyphicon-pencil"></i></span>',
'<span ng-show="editing"><input type="input" ng-model="value.name"><i ng-click="editing = false" class="glyphicon glyphicon-ok"></i></span>',
以上是关于Angularjs模型数组不使用模板更新的主要内容,如果未能解决你的问题,请参考以下文章
AngularJS:从模型数组拼接模型元素时,不会更新 ng-repeat 列表