如何从控制器创建一个继承的隔离范围以生成可重用的指令?这是我的示例代码:
(function (app) {
//declare the Template
var template = function (element, attrs) {
var htmltext =
'<select ' + attrs.type +
' ng-init="getAll(\'' + attrs.classname +
'\');" ng-model="' + attrs.model +
'" ng-options="value.' + attrs.data +
' for value in result"></select>';
return htmltext;
};
app.directive('listData', function () {
return {
restrict: 'E',
controller: 'listController',
controllerAs: 'vm',
scope: { vm: '=' },
template: template
}
});
}(angular.module('app')));
我们如何使用此指令中的多个(仅使用一个控制器)并使用控制器为指令生成的函数的结果。
在此示例中,我有一个getAll
函数,它将$scope.result
从控制器返回给调用者。我希望将这个结果与我给每个指令的ng-model
一起使用。
<div ng-controller="listController">
<list-data type=""
model="person"
classname="Person"
data="Family"
vm="listController">
</list-data>
<list-data></list-data>
<p>{{person.Name}} {{person.Family}}?</p>
和列表控制器:
(function (app) {
app.controller('listController', ['$scope','myservice',function ($scope, myservice) {
//Call GetAll Method From Each Class
$scope.getAll = function (classname) {
myservice.getAll(classname)
.success(function (data, status) {
$scope.result = data;
$scope.status = status;
})
.error(function (data, status) {
$scope.result = data;
$scope.status = status;
});
}
}(angular.module('app')));
和我的服务:
(function (app) {
app.factory('myservice', function ($http,$q) {
return {
getAll: function (classname) {
try {
return $http.get('/api/' + classname + '/GetAll/');
} catch (e) {
window.alert(e.message);
//should Send a error to controller
}
}
}
});
}(angular.module('app')));
答案 0 :(得分:0)
我想你想要这样的东西:
(function (app) {
//declare the Template
var template = function (element, attrs) {
var htmltext =
'<select ' + attrs.type +
' ng-model="model" ng-options="value as value[data] for value in from"></select>';
return htmltext;
};
app.directive('listData', function () {
return {
restrict: 'E',
scope: { data: '@',
classname:'@',
model:'=',
from:'=',
type:'@',
data:'@'
},
template: template,
replace:true,
}
});
app.controller('TestController', ['$timeout', '$scope', function($timeout, $scope){
$scope.data = [];
$timeout(function(){
$scope.data = [{Family:"FOO", Name:"foo"},{Family:"BAR", Name:"bar"}];
});// simulate async fetching
}])
}(angular.module('app', [])));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="TestController">
<h1> this is a test </h1>
<list-data type=""
model="person"
classname="Person"
from="data"
data="Family">
</list-data>
<p>{{person.Name}} {{person.Family}}?</p>
</div>
</div>
&#13;
指令中的一些错误:
<select>
中选择一个人并展示他们的家人。为此,您必须使用as
。ng-options
我添加了什么:
我删除了什么:
link(scope, element, attrs){}
执行提取并将数据绑定到范围。编辑:根据要求,您可以将属性绑定到链接函数中的范围,但是这只能读取数据,而不是更改它们:
link:function(scope, element, attrs){
scope.value = attrs.myAttr;
attrs.$observe('myAttr', function(){
scope.value = attrs.myAttr;
});
}