Angularjs 模型数组未使用模板更新

Angularjs Model Array Not updating with Template

我使用以下代码创建了模板。编辑功能工作正常,但模型正在更新。

在模板中,我已将模型与 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>',