'use strict';
angular.module('$praveen.directives').directive('pvTempUrl',
function ($http, $compile, $log) {
$log.info("Directive Called");
return {
restrict: 'A',
replace:true,
compile: function (telement, tattr, transclude) {
var templateloader = $http.get('../../HelloTemp.html').
success(function (data) {
$log.info("Success-" + data);
telement.html(data);
}).
error(function (data, status) {
$log.warn("Error occured - " + data + " status-" + status);
});
return function (scope, element, attr, controller) {
$log.info("Reached till return part");
templateloader.then(function () {
var compiledHtm = $compile(telement.html())(scope).html();
element.html(compiledHtm);
});
}
}
};
});
错误是在var compiledHtm = $compile(telement.html()(scope));
行需要函数我们可以直接使用模板url而不是编译代码。
编辑:编辑$compile(telement.html())(scope).html();
现在获得编译<input class="ng-pristine ng-valid" type="text" ng-model="txtData">{{ txtData }}
后的HTML
但仍然,ng-model不起作用并显示{{txtData}],因此控制台上也没有错误。
问题发现我绑定了html而不是编译对象
// Code goes here
var mymodule = angular.module('myapp', []);
mymodule.controller('mycontroller', function ($scope) {
});
mymodule.directive('pvTempUrl',
function ($http, $compile, $log, $templateCache) {
$log.info("Directive Called");
return {
restrict: 'A',
replace: true,
compile: function (telement, tattr, transclude) {
var templateloader = $http.get(tattr.pvTempUrl, { cache: $templateCache }).
success(function (data) {
$log.info("Success-" + data);
telement.html(data);
}).
error(function (data, status) {
$log.warn("Error occured - " + data + " status-" + status);
});
return function (scope, element, attr) {
templateloader.then(function () {
var compiledHtm = ($compile(telement.html())(scope));
$log.info("compiled html-" + compiledHtm);
//element.html(compiledHtm);
element.replaceWith(compiledHtm);
$log.info(element.html());
});
};
}
};
});
这会解决您的问题吗?
angular.module('$praveen.directives').directive('pvTempUrl', function($compile, $http, $log, $templateCache) {
$log.info("Directive Called");
return {
restrict: 'A',
replace: true,
compile: function(tElement, tAttrs) {
var templateLoader = $http.get('../../HelloTemp.html', {
cache: $templateCache
}).success(function(data) {
$log.info("Success-" + data);
tElement.html(data);
}).
error(function(data, status) {
$log.warn("Error occured - " + data + " status-" + status);
});
return function(scope, element, attrs) {
templateLoader.then(function(templateText) {
element.html($compile(tElement.html())(scope));
});
};
}
};
});
我还包括一些模板缓存。