【发布时间】:2016-05-16 12:57:52
【问题描述】:
只是从这个链接http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-6-using-controllers阅读一篇文章
像 ng 新手一样,我很难理解他们的代码示例。告诉我一个例子,人们会在没有控制器的情况下编写指令?
他们的代码
(function() {
var app = angular.module('directivesModule');
app.directive('isolateScopeWithController', function () {
var controller = ['$scope', function ($scope) {
function init() {
$scope.items = angular.copy($scope.datasource);
}
init();
$scope.addItem = function () {
$scope.add();
//Add new customer to directive scope
$scope.items.push({
name: 'New Directive Controller Item'
});
};
}],
template = '<button ng-click="addItem()">Add Item</button><ul>' +
'<li ng-repeat="item in items">{{ ::item.name }}</li></ul>';
return {
restrict: 'EA', //Default in 1.3+
scope: {
datasource: '=',
add: '&',
},
controller: controller,
template: template
};
});
}());
指令用法:
属性:<div isolate-scope-with-controller datasource="customers" add="addCustomer()"></div>
元素:<isolate-scope-with-controller datasource="customers" add="addCustomer()"></isolate-scope-with-controller>
我们如何将客户数据直接传递给指令。基本上我们在控制器中有模型并填充模型,然后通过隔离范围或指令使用控制器范围将该模型数据传递给指令。我对上面的代码如何工作感到非常困惑,请帮助我理解。谢谢
【问题讨论】:
-
该代码具有误导性。指令有控制器。
标签: angularjs angularjs-directive angularjs-scope