javascript - ng-repeat 如何处理其中内容的范围变量

标签 javascript angularjs angularjs-directive angularjs-ng-repeat

全部:

我是 AngularJS 指令范围的新手。我想知道是否有人可以大致谈谈 ng-repeat 如何处理其中 html 中指定的变量的过程。

例如:

<html ng-app="app">
<body ng-controller="main">
    <div ng-repeat="d in data" ng-init="edited_odd_times=false" ng-click="editdata()">
        <span>{{d}}: {{edited_odd_times}}</span>
    </div>
</body>


<script>
    var app = angular.module("app", []);
    app.controller("main", function($scope){
        $scope.data = [1, 2, 3, 4];
        $scope.data2 = [{d:1}, {d:2}, {d:3}, {d:4}];
        $scope.editdata = function(){
            // Here is my confuse, how can I access the d and edited_odd_times inside ng-repeat without putting them as paramters

        }
    });
</script>
</html>

我想知道的是:

[1]。我想知道在 $scope.editdata 中如何更改 d 和 edited_odd_times 而不将它们作为参数,或者如何访问 ng-repeat 生成的范围?

[2]。为什么 ng-repeat 会影响其中 HTML 中的变量,而指令(比如我想定义一个指令像 ng-repeat 但只是不重复)与scope:true 和 transclude 不能影响那个 HTML 中的变量吗?

谢谢

最佳答案

您问题的直接答案如下。

[1] 您应该认为没有办法从其父范围访问子范围中生成的值。 换句话说, Controller 作用域不应该访问指令中生成的作用域值。

[2] 你可以使用 ngTransclude。请再次查看官方文档。

我想您想要实现的目标如下所示。

在 Html 中。

<div ng-app="testapp" ng-controller="testctrl">
    <div ng-repeat="d in data">
        {{d}}
    </div>
</div>

在 Controller 代码中。

angular.module('testapp', [])
.controller('testctrl', function($scope){
    $scope.data = [1,2,3];
    angular.forEach($scope.data, function(item, i){
        if (i%2==0){
            $scope.data[i] = item + '(edited)';
        }
    });
})

jsfiddle is here.

希望对您有所帮助。 :)

关于javascript - ng-repeat 如何处理其中内容的范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31039044/

相关文章:

angularjs - 是否可以使用范围:true从Angular Directive更新父范围。

javascript - 无法访问 Angular Directive 模板函数中的属性实际值

javascript - 使用 Grunt 的多个文件夹和文件

javascript - react : 'p' is not defined no-undef in component file

angularjs - 使用 httpBackend [Protractor] 模拟 API

javascript - 嵌套 ui-sref 时防止调用父级

javascript - 有没有办法在不访问后端的情况下处理 CORS?

angularjs - 取消绑定(bind) Angular 元素

javascript - 我创建了一个可以对数字进行因式分解的网页。我已经创建了该功能。现在我需要创建一个函数来显示我的数学。

JavaScript:覆盖 Date.prototype.constructor