我使用以下代码创建了模板。编辑功能可以正常工作,但是模型正在更新。
在模板中,我已将模型与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>
答案 0 :(得分:1)
看看这一点,问题在于,您是通过两种方式绑定字符串而不是对象,这意味着您实际上没有得到好处: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>',