0

I want to add all my elements from my template to my $scope. I want them to be accessible like c# or java elements in the code.

for example if i have this HTML template

<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>

And here is a possible controller:

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')
}

Is there a best case to do this or is there a good way to add all my HTML elements to the scope ? I want clean "object oriented" javascript code.

9
  • 1
    You can access anything within the controller using selectors. eg $('#div1'). Why are you doing this though? If you are going to manipulate the elements, its best to do it in a directive Commented Feb 5, 2015 at 23:33
  • That would be the opposite of a clean "object-oriented" code. You should respect the Model-View-Controller approach, where all the View stays in your HTML and is updated according to your model (the $scope). Commented Feb 5, 2015 at 23:36
  • okay i have a background color of a div and want to manipulate it because it is used as a color preview how would that be done without knowing the element ? can i acces div1 or div2 in my directive "ch-options-div" ? Commented Feb 5, 2015 at 23:39
  • 1
    Theres multiple ways to do that. If you do no want to go down the directive path, you can do it the 'angular way' by manipulating a model and applying it to a property like ng-class. Here is an example: jsfiddle.net/skriblez/dqfwvyso Commented Feb 6, 2015 at 0:02
  • 1
    Well, in that case it may be best to do it in a directive, here is an updated fiddle with the directive now doing the manipulation dependent on the RGB colour passed through: jsfiddle.net/skriblez/dqfwvyso/2 Commented Feb 6, 2015 at 0:32

1 Answer 1

1

You can use a directive to achieve this.

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

Here is an example of you to use the directive: http://jsfiddle.net/skriblez/dqfwvyso/4/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.