Skip to content

Instantly share code, notes, and snippets.

@jigewxy
Created July 18, 2017 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jigewxy/791479aa9b56e90e9223f63521ffdeff to your computer and use it in GitHub Desktop.
Save jigewxy/791479aa9b56e90e9223f63521ffdeff to your computer and use it in GitHub Desktop.
<!doctype html>
<html >
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<script type="text/javascript">
var Dm = angular.module('testDirective',[]);
Dm.controller('DmCtrl', function($scope) {
$scope.name = "cliff";
$scope.money="123";
});
Dm.directive('moneyWrap', function() {
function link(scope, element, attrs) {
element.find('span#original').css('color', 'red');
//you can't find the original element in link function
console.log(attrs.money + attrs.name);
element.append(scope.money + '$');
console.log(JSON.stringify(attrs, null, '\t'));
}
return {
replace: true,
scope: {money:'@',
name: '@'},
transclude: true,
template: "<div>that's my money {{money}} <span ng-transclude></span> </div>",
link: link
};
});
</script>
</head>
<body ng-app="testDirective">
<div class="wrap" ng-controller="DmCtrl">
<h2>用来测试directive的例子</h2>
<p money-wrap money="{{money}}" name="{{name}}"><span id="original">original content </span></p>
</div>
</body>
</html>
@jigewxy
Copy link
Author

jigewxy commented Jul 18, 2017

  1. transclude element must be defined in the directive with "ng-transclude" attribute;
  2. any variables in the private scope can be accessed from "attrs" argument in link function.
  3. html code in template needs to be wrapped in one closed tag., or else it will throw error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment