如何在使用 AngularJS ng-repeat 时初始化本地范围内的属性

How to initialize property in local scope when using AngularJS ng-repeat

本文关键字:初始化 范围内 属性 ng-repeat AngularJS      更新时间:2023-09-26

我有一个字符串和按钮列表,这些字符串和按钮可以更改本地范围内每个字符串的颜色属性。每个新添加的字符串都将是黑色的,因为从控制器范围获取颜色属性。如何在新字符串的本地范围内初始化颜色属性?

这只是一个例子来证明我的问题。因此,在实际项目中,我无法将新属性添加到列表(例如当前颜色:"红色")或其他内容。我只想知道:创建此范围时,如何将值设置为本地范围内的属性。

var MyApp = angular.module('MyApp', []);
        MyApp.controller('MyController', function ($scope) {
            $scope.color = 'Black';
            $scope.list = [
                { text: 'text1' },
                { text: 'text2' },
                { text: 'text3' }
            ]
            $scope.AddNewText = function () {
                $scope.list.push({ text: 'text' + ($scope.list.length + 1) });
            }
        });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<div ng-app="MyApp">
        <div ng-controller="MyController">
            <div ng-repeat="item in list">
                <span style="color:{{color}}">{{item.text}}</span>
                <button data-ng-click="color = 'Red'">Red</button>
                <button data-ng-click="color = 'Green'">Green</button>
                <button data-ng-click="color = 'Blue'">Blue</button>
                <button data-ng-click="color = 'Black'">Black</button>
            </div>
            <button data-ng-click="AddNewText()">Add new text</button>
        </div>
    </div>

仅使用 ng-style 指令更改一个将处理颜色默认值的 html 行。

<span ng-style="{'color':color||'Black'}">{{item.text}}</span>

你的 html 将如下所示

<div ng-app="MyApp">
    <div ng-controller="MyController">
        <div ng-repeat="item in list"> 
            <span ng-style="{'color':color||'Black'}">{{item.text}}</span>
            <button data-ng-click="color = 'Red'">Red</button>
            <button data-ng-click="color = 'Green'">Green</button>
            <button data-ng-click="color = 'Blue'">Blue</button>
            <button data-ng-click="color = 'Black'">Black</button>
        </div>
        <button data-ng-click="AddNewText()">Add new text</button>
    </div>
</div>

无需从控制器设置任何颜色值。在这里摆弄

希望我理解你的问题。谢谢。

ng-repeat创建自己的代码。要初始化本地作用域,可以使用ng-init .

<div ng-repeat="item in list" ng-init="color = 'red'">
     <span style="color:{{color}}">{{item.text}}</span>
</div>

使 $scope.list 一个包含文本和颜色的对象数组。

 $scope.list = [
                { text: 'text1',color: 'black' },
                { text: 'text2',color: 'black' },
                { text: 'text3',color: 'black' }
            ]

目录:

        <span style="color:{{item.color}}">{{item.text}}</span>
            <button data-ng-click="item.color = 'Red'">Red</button>

如果要初始化而不列出,则需要使用$watch。

$scope.$watch('list', function() {
       $scope.color = 'black';
       console.log('list has changed, do whatever you want');
   });