directive 实例讲解
下面的示例都围绕着上面所作的参数说明而展开的。
directive声明实例
// 自定义directive
var myDirective = angular.modeule('directives', []);
myDirective.directive('myTest', function() {
return {
restrict: 'EMAC',
require: '^ngModel',
scope: {
ngModel: '='
},
template: '<div><h4>Weather for {{ngModel}}</h4</div>'
};
});
// 定义controller
var myControllers = angular.module('controllers', []);
myControllers.controller('testController', [
'$scope',
function($scope) {
$scope.name = 'this is directive1';
}
]);
var app = angular.module('testApp', [
'directives',
'controllers'
]);
<body ng-app="testApp">
<div ng-controller="testController">
<input type="text" ng-model="city" placeholder="Enter a city" />
<my-test ng-model="city" ></my-test>
<span my-test="exp" ng-model="city"></span>
<span ng-model="city"></span>
</div>
</body>
复制代码
template与templateUrl的区别和联系
templateUrl其实根template功能是一样的,只不过templateUrl加载一个html文件,上例中,我们也能发现问题,template后面根的是html的标签,如果标签很多呢,那就比较不爽了。可以将上例中的,template改一下。
myDirective.directive('myTest', function() {
return {
restrict: 'EMAC',
require: '^ngModel',
scope: {
ngModel: '='
},
templateUrl:'../partials/tem1.html' //tem1.html中的内容就是上例中template的内容。
}
});
复制代码
scope重定义
//directives.js中定义myAttr
myDirectives.directive('myAttr', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
template: 'Name: {{customerInfo.name}} Address: {{customerInfo.address}}<br>' +
'Name: {{vojta.name}} Address: {{vojta.address}}'
};
});
//controller.js中定义attrtest
myControllers.controller('attrtest',['$scope',
function($scope) {
$scope.naomi = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
$scope.vojta = {
name: 'Vojta',
address: '3456 Somewhere Else'
};
}
]);
// html中
<body ng-app="testApp">
<div ng-controller="attrtest">
<my-attr info="naomi"></my-attr>
</div>
</body>
复制代码
其运行结果如下:
Name: Naomi Address: 1600 Amphitheatre //有值,因为customerInfo定义过的
Name: Address: //没值 ,因为scope重定义后,vojta是没有定义的 |