AngularJs控制器从模板中添加所有html元素

AngularJs controller add all html elements from template

本文关键字:html 元素 添加 控制器 AngularJs      更新时间:2023-09-26

我想将模板中的所有元素添加到$scope中。我希望它们像代码中的c#或java元素一样可以访问。

例如如果我有这个HTML模板

<div ch-options-div id="chOptions" ng-controller="chOptionsCtrl">
    <span>Options</span>
    <div id="chOptionsWrapper">
        <div id="div1">
        </div>
        <div id="div2"></div>
        <div id="div3"></div>
    </div>
</div>

这里有一个可能的控制器:

var chOptions = angular.module('chOptions',[]);
chOptions.controller('chOptionsCtrl', function ($scope,$document,$element) 
{     
    //select all elements by id and add them to scope
    $scope.chOptionsWrapper = document.getElementById('chOptionsWrapper');
    //or with jquery
    $scope.div1 = $('#div1')
}

有没有最好的方法来做到这一点,或者有没有一个好的方法来将我的所有HTML元素添加到范围中?我想要干净的"面向对象"javascript代码。

您可以使用指令来实现这一点。

.directive('box', function () {
    return {
        scope: {
            rgb: '='
        },
        link: function (scope, elem, attrs) {
            scope.$watch('rgb', function () {
                angular.element(elem).css('background-color', 'rgb(' + scope.rgb + ')');
            });
        }
    }
}

以下是使用该指令的示例:http://jsfiddle.net/skriblez/dqfwvyso/4/