jquery - How to get and set an attribute value for a HTML tag using AngularJS? -


i trying find best way & set value attribute in html tag using angularjs. example:

<!doctype html> <html> <head> <meta charset="utf-8"> <title>my website</title> </head> <body>     <h1>title</h1>      <p>praragraph1</p>      <p data-mycustomattr="1234567890">paragraph 2</p>      <p>paragraph 3</p>      <footer>footer</footer> </body> </html> 

then, when call url '/home', value data-mycustomattr (that use calculation), , replace "1",

and if url '/category', value data-mycustomattr, , replace "2".

with jquery simple:

$("#mypselector").attr('data-mycustomattr'); 

or

$("#mypselector").attr('data-mycustomattr','newvalue'); 

i used jquery code, putting inside controllers, , working fine. far read, might bad practice.

however, solutions found, uses directives, big such simple task. wondering if combining jquery , angularjs @ special circumstances may not bad after all.

what think? have better solution & set attribute's values?

answer based on jonathan's reply:

<!doctype html> <html> <head> <meta charset="utf-8"> <title>my website</title> </head> <body>     <h1>title</h1>      <p>praragraph1</p>      <p data-mycustomattr="{{mycustomattr}}">paragraph 2</p>      <p>paragraph 3</p>      <footer>footer</footer> </body> </html> 

then, controllers, inserted:

$scope.mycustomattr = '1'; 

and reading:

if ($scope.mycustomattr == '1'){     // code } 

tested , working fine.

in general want have model drive view , avoid making changes dom directly. 1 way of achieving have controller set value of attribute based on route. bind value desired attribute

 var mediaapp = angular.module('mediaapp',[]);   mediaapp.config(['$routeprovider', function($routeprovider) {       $routeprovider.when('/video', {templateurl: 'video.html',   controller: 'videoctrl'});       $routeprovider.when('/audio', {templateurl: 'audio.html',   controller: 'audioctrl'});  }]);   mediaapp.controller('videoctrl',function($scope){       $scope.customattributevalue = "1";   });   mediaapp.controller('audioctrl',function($scope){      $scope.customattributevalue = "2";  }); 

then in view templates bind attribute.

 <h2>videos</h2>  <div data-customattr="{{customattributevalue}}">  </div> 

and audio template...

 <h2>audio</h2>  <div data-customattr="{{customattributevalue}}">  </div> 

when navigating route /video data-customattr have value of 1, when navigating route /audio data-customattr have value of 2.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -