0

I have an Angular app which looks something like an iPad app. There is a navbar with buttons and dropdown menus. The navbar is declared in my index.html file. Now in my different pages, i want to add functionality to the navbar. Right now i am adding buttons to the navbar like this

    $rootScope.actionButtons.push({
    icon:   'icon-history',
    content:    '<select ng-change="previewRevision()" ng-model="revision">\
                    <option value="">--Backlog--</option>
                    <option ng-repeat="old in journal.backlog" value="{{old.revision}}">Revision {{old.revision}}</option>
                </select>',
    title:  'Visa backlog'});

The content in this view opens up in a popover when a button in the navbar is pressed. However, since the markup for rendering the button is outside of the controller no data is bound to it, which makes it kind of useless.

How can i bind data which is outside of the current scope?

1 Answer 1

2

Angular doesn't know about your content. To make it work we need to compile this source by using $compile service.

So lets create "compilator":

.directive( 'compileData', function ( $compile ) {
  return {
    scope: true,
    link: function ( scope, element, attrs ) {

      var elmnt;

      attrs.$observe( 'template', function ( myTemplate ) {
        if ( angular.isDefined( myTemplate ) ) {
          // compile the provided template against the current scope
          elmnt = $compile( myTemplate )( scope );

            element.html(""); // dummy "clear"

          element.append( elmnt );
        }
      });
    }
  };
});

Add directive to HTML like:

 <div compile-data template="{{actionButtons.content}}"></div>

After compilation, you will bind your scope with under mentioned HTML

           <select ng-change="previewRevision()" ng-model="revision">\
                <option value="">--Backlog--</option>
                <option ng-repeat="old in journal.backlog" value="{{old.revision}}">Revision {{old.revision}}</option>
            </select>

Hope it will help

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

3 Comments

Upvote because it looks cool and seems like you know what you're talking about. Accepting when i've tried it :)
Am i thinking correct here; in my controller xCtrl i bind $rootScope.actionButtons.content to lets say the string literal {{myvalue}}. In xCtrl i will then set $scope.myvalue = "test" and then the data will be bound even though the markup is outside the view-controller (which is the correct term here?)?
Sorry but its hard to read from comment line, i posted Fiddle, configure it for your purposes

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.