【发布时间】:2014-11-08 17:49:05
【问题描述】:
我有一个独立范围的指令如下:
application.directive("myDirective",function(){
return {
restrict: "A",
scope: {myDirective:"="},
link : function(scope) {
console.log("My directive: ",scope.myDirective) // works fine
scope.person={name:"John",surname:"Doe"}
scope.hello=function(){
console.log("Hello world!")
}
}
}
})
对应视图:
<div my-directive='{testValue:3}'>
Testvalue: {{myDirective}}<br/>
Hello {{person}}
<button ng-click="hello()">Say hello</button>
</div>
而且似乎我不能使用范围内声明的任何字段。鉴于“myDirecive”和“person”字段为空白,并且当我按下按钮时未执行范围的“hello”功能。
当我将 scope="true" 传递给指令但在隔离范围内不起作用时,它可以正常工作。
我在这里遗漏了什么,或者没有办法将变量引入指令的隔离范围?
更新
更新的问题介绍了为什么我不想使用静态模板。我想要达到的效果是制作指令,允许上传任何通过rest/json获取表单初始数据的html表单。整个过程相当复杂且特定于应用程序,因此我无法使用任何可用的表单库。我在下面介绍用例的简化版本:
更新后的指令
application.directive("myForm",function(){
return {
restrict: "A",
scope: {myForm:"="},
link : function(scope) {
console.log("Form parameters: ",scope.myForm) // works fine
scope.formData=... // Get form initial data as JSON from server
scope.submitForm=function(){
// Send scope.formData via REST to the server
}
}
}
})
我想使用这种形式的情况。当然我想用不同的形式多次使用这个指令。
<form my-form='{postUrl:'/myPostUrl',getFormDataUrl:'/url/to/some/json}'>
<div>Form user: {{formData.userName}} {{formData.userSurname}}
<input type="text" ng-model="formData.userAge" />
<input type="text" ng-model="formData.userEmail" />
<button ng-click="submitForm()">Submit</button>
</form>
我希望这能解释为什么我不能在这种情况下使用一个静态 html 模板。
也许有人可以解释为什么这适用于 scope="true" 并且在一个孤立的范围内我无法访问任何范围内的变量?
【问题讨论】:
标签: angularjs