AngularJS-为什么我的指令隔离范围变量未定义?
我有以下几点: 当我运行此命令时,templateUrl在作用域中未定义。为什么? 我的假设是,它试图在父作用域中找到名为template.html的变量,但找不到,因此它将其分配给未定义的。如果是这样,我如何将其作为字符串而不是范围变量传入 Html:AngularJS-为什么我的指令隔离范围变量未定义?,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,我有以下几点: 当我运行此命令时,templateUrl在作用域中未定义。为什么? 我的假设是,它试图在父作用域中找到名为template.html的变量,但找不到,因此它将其分配给未定义的。如果是这样,我如何将其作为字符串而不是范围变量传入 Html: .js var-app=angular.module(“myApp”,[]); app.controller(“TestCtrl”,函数($scope){ $scope.testModel={} }); app.directive(“te
.js
var-app=angular.module(“myApp”,[]);
app.controller(“TestCtrl”,函数($scope){
$scope.testModel={}
});
app.directive(“testDirective”,函数(){
返回{
限制:'E',
范围:{
型号:“=ngModel”,
templateUrl:“”
},
模板:“”,
链接:函数(范围、元素、属性){
console.log(scope.templateUrl);//我解决了我的问题。我需要使用@而不是=
app.directive("testDirective", function () {
return {
restrict: 'E',
scope: {
model: "=ngModel",
templateUrl: "@"
},
template: "<div ng-include='templateUrl'></div>",
link: function (scope, element, attrs) {
console.log(scope.templateUrl); // <-- Works perfectly
}
}
});
app.directive(“testDirective”),函数(){
返回{
限制:'E',
范围:{
型号:“=ngModel”,
模板URL:“@”
},
模板:“”,
链接:函数(范围、元素、属性){
console.log(scope.templateUrl);//只需更改范围:
scope: {
templateUrl: "@"
},
您将获得输出“template.html”
关键点是“=”和“@”之间的区别。您可以参考。在指令中使用等号(=)时,必须在$scope下定义此属性,否则它将不起作用,它将产生错误“”。请参阅角度文档。您是否可以尝试templateUrl:“=?”或在$scope下
根据有角度的文件
<!-- ERROR because `1+2=localValue` is an invalid statement -->
<my-directive bind="1+2">
<!-- ERROR because `myFn()=localValue` is an invalid statement -->
<my-directive bind="myFn()">
<!-- ERROR because attribute bind wasn't provided -->
<my-directive>
若要解决此错误,请始终使用具有双向数据绑定的作用域属性的路径表达式:
<my-directive bind="some.property">
<my-directive bind="some[3]['property']">
您的解决方案就在这里指令API已移动到$compile。[详细解释差异的优秀答案:
<!-- ERROR because `1+2=localValue` is an invalid statement -->
<my-directive bind="1+2">
<!-- ERROR because `myFn()=localValue` is an invalid statement -->
<my-directive bind="myFn()">
<!-- ERROR because attribute bind wasn't provided -->
<my-directive>
<my-directive bind="some.property">
<my-directive bind="some[3]['property']">