0

I have an angular directive:

app.directive('myStyle', function($location) {
  return {
    scope: {
      myCSSFile: "="
    },
    //template: '<link href="style.css" rel="stylesheet" />',
    template: '<link href="{{ myCSSFile }}.css" rel="stylesheet" />',
    link: function(scope,el, attr) {
      var absUrl = $location.absUrl();
      console.log(absUrl);

      if (absUrl == 'http://run.plnkr.co/KDRUOzkRgvgCzdzy/') {
        console.log("Found");
        scope.myCSSFile = 'style';
      }
      else {
        console.log("Not found");
        scope.myCSSFile = 'style2';
      }      
    }
  };
});

How do i bind a value to {{ myCSSFile }} within the template based on the function within my link?

Plunkr: http://plnkr.co/edit/I6om40ZfRZbETwsbl3MO?p=preview

4
  • 1
    stackoverflow.com/q/15485288/3556874 Commented Mar 9, 2015 at 13:57
  • @NaeemShaikh - thanks for the link, i get i have to set scope to true and use $complie... but how do i return jqLiteWrappedElement to the template? Also, there is a watch on pluginui i dont see that i actually need to watch anything for this as it will only ever be triggered on page load. Commented Mar 9, 2015 at 14:04
  • @NaeemShaikh - see this fork: plnkr.co/edit/Pp2PkRcHb07EqNweJJfR?p=preview Commented Mar 9, 2015 at 14:12
  • Updated the code without the .watch Commented Mar 9, 2015 at 14:17

1 Answer 1

1

You can't use two way binding for myCSSFile with undefined value. So if you want isolated scope you can change it to bind with @, or create a new scope:

scope: true, // plunker1
scope: { // plunker2
    myCSSFile = '@'
},

Punker1 , Plunker2

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

4 Comments

your plunker link.. Its still showing as scope: true... no comment about scope: { myCSSFile = '@' },
that's because you can use either one of them, i've updated my answer.
Thanks... Although the output to the user is as expected, looking at the Network http requests, you can see errors: NetworkError: 400 Bad Request - run.plnkr.co/diEAdEJme62ZQgV8/%7B%7B%20myCSSFile%20%7D%7D.css"
i dont see 400.. i get cancelled status because myCSSFile was changed right after it was placed in the DOM. If you don't want that i guess you need to use $compile

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.