简体   繁体   中英

accessing angularjs scope variables and assigning it to script tag attributes in html

I have some data stored in controller as scope variables and want to assign them to the attributes of a script tag which is implemented in html and used for payment gateway.

following are the scope variables:

$scope.selectedPlan = plan;

here the selectedPlan is array of objects of data with following values :

plan_id: 3
plan_name: "Basic"
price: "30"
validity_text: "30 days"

need to access some of above values like price in a script tag which is implemented in html file. Following is the code for script tag:

<script
                src="https://checkout.stripe.com/checkout.js" class="stripe-button"
                data-key="pk_test_ghxvjhdasfwdadsd"
                data-amount="{{selectedPlan.price}}*100"
                data-name="Amazing Test"
                data-description="Amt: $ {{selectedPlan.price}}"
                data-image="http://test.com/assets/Images/globe.png">
              </script>

Here in above written code the selectedplan is the scope object of controller and price attribute needs to be assigned to the data-amount and data-description attribute of script tag. As i am new to angularjs dont know how to implement it.

Please help me achieve what i want.

If you want to dynamically compute attributes for you script tag, you need to use the ng-attr directive. The code becomes:

<script
   src="https://checkout.stripe.com/checkout.js"
   class="stripe-butt"
   data-key="pk_test_4RvHCPGrrtHK9dW0vqO938ge"
   ng-attr-data-amount="{{selectedPlan.price*100}}"
   data-name="Amazing Minds"
   ng-attr-data-description="Amt: $ {{selectedPlan.price}}"
   data-image="http://itutor.staging.broadweb.com.au/assets/Images/itutorglobe.png">
</script>

However Angular it not meant to dynamically modify a <script> tag. I have never tried this myself, but I am pretty sure the script tag will only be read once with the initial parameters, even before angular has the time to compile them.

One way to work around that would be to compile that code with Angular's $compile service before appending it to the DOM.

However this is probably over-complicating things. You'd better create it manually. Here is how to do that: Dynamically create a script tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM