2
我有一個列表,當你點擊一個項目時,它會拋出一個包含該特定項目的詳細信息的彈出窗口。我已經設置了一個指令,用於編譯一個新的popover指令,並在關閉時刪除/銷燬它。
這是一個工作example。
//JS
angular.module('compileExample', [])
.controller('CompileController', ['$scope', function($scope) {
$scope.things = [{name:'One'},{name:'Two'},{name:'Three'}];
}])
.directive('primaryDir', ['$compile', function($compile) {
return {
scope: {},
restrict: 'A',
link: function(scope, element, attrs) {
element.on('click', function() {
/* NOTE: The string template in template would get large and is nasty. */
var data = JSON.parse(attrs.primaryDirData),
template = $compile('<div class="panel panel-cover js-bind">Data from '+data.name+'<button ng-click="remove()">Remove</button></div>')(scope);
angular.element('.container').append(template);
scope.remove = function() {
angular.element('.js-bind').remove();
};
});
}
};
}]);
// HTML
<div ng-app="compileExample">
<h2 class="inject">Todo</h2>
<div ng-controller="CompileController" class="container">
<div class="well" ng-repeat="thing in things" primary-dir primary-dir-data="{{thing}}">
{{thing.name}}
</div>
</div>
</div>
問題
在我指導的鏈接函數的字符串模板是討厭和它會得到更大。所以我決定將模板渲染分解成它自己的指令,這樣我就可以使用指令的API進行模板加載。工作example here。但現在它沒有通過正確的數據,我得到舊的空/ [對象對象]。如果任何人有任何建議,即時建立數據驅動的指令,我想確定一些最佳實踐。我沒有嫁給$ compile,它似乎是最高性能的選擇。
// JS
angular.module('compileExample', [])
.controller('CompileController', ['$scope', function($scope) {
$scope.things = [{name:'One'},{name:'Two'},{name:'Three'}];
}])
.directive('template', function() {
return {
replace: true,
template: '<div class="panel panel-cover js-bind">Data from <strong>{{foo}}</strong> <button ng-click="remove()">Remove</button></div>',
link: function(scope, element, attrs) {
scope.foo = !attrs.data ? 'bar' : attrs.data;
}
};
})
.directive('primaryDir', ['$compile', function($compile) {
return {
scope: {},
link: function(scope, element, attrs) {
var data = JSON.parse(attrs.primaryDirData);
element.on('click', function() {
var template = $compile('<div template data="'+data+'"></div>')(scope);
scope.$apply(function(){
angular.element('.container').append(template);
});
});
scope.remove = function() {
angular.element('.js-bind').remove();
};
}
};
}]);