Angular directive scope
真心觉得这篇最好http://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/
这个也不错http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope
HTML
<div class="directive" my-directive name="{{name}}" color="{{color}}" equal="equal" eq="eq" reverse="reverseName()" ></div> name和color是单向绑定的 虽然在directive中所做的改动可以反映到页面上(看起来一点都不像单向绑定呢) 实际上这是因为directive中的模板使用了ng-model的缘故 从下面的值可以看出究竟是否改动 因为name和color是单向绑定 所以即使在directive中改变name和color的值 这里显示的仍是controller赋予的初始值 equal就不同了 因为是双向绑定 <span>{{name}}</span><span>{{color}}</span> <span>{{equal}}</span>
controller
function test1Ctrl($scope) { $scope.var1 = 'var1'; $scope.name = "Harry"; $scope.color = "#333333"; $scope.equal = 'equal first'; $scope.eq = 'eq2 first'; $scope.reverseName = function(){ $scope.name = $scope.name.split("").reverse().join(""); }; $scope.randomColor = function(){ $scope.color = '#'+Math.floor(Math.random()*16777215).toString(16); }; }
directive
function myDirective($compile) { return { restrict: "EA", repalce: true, scope: { name: "@", color: "@",// 单向绑定 页面中对值得改动将反映到js中 eq: "=", equal: "=",// 双向绑定 reverse: "&" }, template: [ "<div class='line'>", "Name : <strong>{{name}}</strong>; Change name:<input type='text' ng-model='name' /><br/>", "</div><div class='line'>", "Color : <strong style='color:{{color}}'>{{color|uppercase}}</strong>;<br/>", "Equal : <strong>{{equal|uppercase}}</strong>; Change equal:<input type='text' ng-model='equal' /><br/></div>", "eq : <strong>{{eq|uppercase}}</strong>; Change eq:<input type='text' ng-model='eq' /><br/></div>", "<br/><input type='button' ng-click='reverse()' value='Reverse Name'/>", "<input type='button' ng-click='setName()' value='set name '/>", "<input type='button' ng-click='showColor()' value='show color '/>", "<input type='button' ng-click='setColor()' value='set color '/>", "<input type='button' ng-click='showEqual()' value='show equal '/>", "<input type='button' ng-click='setEqual()' value='set equal '/>" ].join(""), link: function($scope, $element, $attrs){ $scope.setName = function(){ $scope.name = 'na!me'; } $scope.showColor = function(){ console.log($scope.color); }; $scope.setColor = function(){ $scope.color = '#aaaaaa'; } $scope.showEqual = function(){ console.log($scope.equal); } $scope.setEqual = function(){ $scope.equal = 'equal set!'; } } }; }