在ng-repeat之外创建一个新范围

时间:2016-07-18 14:26:24

标签: javascript angularjs

这个想法是如何通过按文本旁边的按钮来修改文本列表。我们也可以将它应用于列表之外的标题文本。

HTML:

<div ng-controller="TextController">
    <div class="title">
        <span>{{ text }}</span>
        <button ng-click="edit()">Edit</button>
    </div>

    <ul>
        <li ng-repeat="text in list">
            <span>{{ text }}</span>
            <button ng-click="edit()">Edit</button>
        </li>
    </ul>
</div>

JavaScript的:

angular.module("app").
    controller("TextController", function($scope) {
        $scope.text = "hello";
        $scope.list = [....]; // list of texts;

        $scope.edit = function() {
            this.text += " world";
        };
    });

我不确定我是否以正确的方式写作。但是,一切正常,除了标题中的编辑按钮,当我试图仅编辑标题时,它意外地编辑了其子范围内的所有文本。

我尝试做的是给标题一个新范围,使按钮不会影响其他文本,因为它不是任何范围的父级。

4 个答案:

答案 0 :(得分:0)

为什么不为ng-repeat使用另一个变量名(我已经制作了第二个text =&gt; txt)。最好有单独的函数来更新列表和文本,但如果需要,可以尝试

<div ng-controller="TextController">
    <div class="title">
        <span>{{ text }}</span>
        <button ng-click="edit()">Edit</button>
    </div>

    <ul>
        <li ng-repeat="txt in list">
            <span>{{ txt }}</span>
            <button ng-click="edit($index)">Edit</button>
        </li>
    </ul>
</div>

视图传递数组元素的$ index:

    $scope.edit = function(listIndex) {
        if(listIndex) $scope.list[listIndex] += " world"
        else $scope.text += " world";
    };

答案 1 :(得分:0)

是的,你要做的是对的:

{{text}}变量绑定到同一控制器范围。因此编辑按钮只会更新该值,使其随处更改

答案 2 :(得分:0)

您应该尝试更新$ scope.list值: 更新范围时,html将呈现。

$scope.edit = function() {
    $scope.list[this.$index] +=  " world";
};

请查看演示: http://jsfiddle.net/Lvc0u55v/7050/

答案 3 :(得分:0)

你可以创建一个&#34; include&#34;结合ng-template,以便获得新的范围。

http://jsfiddle.net/pfeq0mwe/3/

.\SetFileExecutable.ps1" -comment "Marking file as executable" -fileRelativePath mvnw -repositoryRoot "c:\myrepo"
相关问题