1、指令属性取值:通过attr.someAttribute属性名字获取
以下,通过$eval(attr.data)获取value
<div ng-controller="personCtrl" ng-init="person={name:'wjx',age:24,gender:'男'}">
<person></person>
</div>
var module = angular.module("app",[]); module.directive("person",function(){
return { restrict:"EA",
replace:true,
template:"<div>",
link:function(scope,element,attr){ var person = scope.$eval(attr.data); element.append("<div>name : " + person.name + "</div>")
.append("<div>gender : " + person.gender + "</div>")
.append("<div>age : " + person.age + "</div>")
}
}
});
2、通过控制器对指令赋值,关键代码就是在控制器中声明也是我比较喜欢的做法
var module = angular.module("app",[]);
module.controller("personCtrl",function($scope){
$scope.person= {name:'wjx',age:24,gender:'男'};
});
module.directive("person",function(){
return { restrict:"EA",
replace:true,
template:"<div>",
link:function(scope,element,attr){ var person = scope.person; element.append("<div>name : " + person.name + "</div>")
.append("<div>gender : " + person.gender + "</div>")
.append("<div>age : " + person.age + "</div>")
}
}
});