如何在自定义指令Angularjs中合并表达式

时间:2015-02-09 00:21:01

标签: angularjs angularjs-scope angular-directive angularjs-templates

我试图解决这个问题。假设我有这个自定义指令:

app.directive("selectInput",function($compile){
return {
    restrict: "E",
    templateUrl: 'js/angular-app/test.html',
    scope: {                
        formName:'=',
        inputName:"=",
        nameInput: "@",
        ngModel: "=",
    },
    transclude: true,
    replace: true,
    link: function(scope, element, attrs, ctrl) {   
        ...             
    },
}});

这是我的templateurl test.html

<div
class="form-group"
ng-class="{'has-error has-feedback': formName.inputName.$invalid}"> 
<input type="text" name="{{nameInput}}" ng-model="ngModel"/></div>

和电话

<form name="form" class="simple-form" novalidate>
<select-input 
    form-name="form"                       
    input-name="fClase"            
    name-input="fClase"
    ng-model="inputmodel">
</select-input></form>

问题出在test.html模板中,表达式formName.inputName.$invalid不起作用,我尝试{{formName}}.{{inputName}}.$invalid并且没有,我也尝试更改&, @ ... =?的指令定义中的参数。

我无法合并这些表达式,我感谢任何帮助。

更新,解决问题(感谢Joe Enzminger):

最后,我改变了指令:

app.directive("selectInput",function($compile){
return {
    restrict: "E",
    templateUrl: 'js/angular-app/test.html',
    scope: {           
        inputName: "@",
        ngModel: "=",
    },
    require: ["^form"],
    replace: true,
    link: function(scope, element, attrs, ctrl) {  
        scope.form = ctrl[0]; 
        ...             
    },
}});

请注意表格attr为ctrl。

模板test.html

<div
class="form-group"
ng-class="{'has-error has-feedback': form[inputName].$invalid}"> 
<input type="text" name="{{nameInput}}" ng-model="ngModel"/></div>

此处formName.inputName.$invalid更改form[inputName].$invalid

最后是电话

<form name="form" class="simple-form" novalidate>
<select-input        
    input-name="fClase"   
    ng-model="inputmodel">
</select-input></form>

我希望有用

1 个答案:

答案 0 :(得分:1)

这是一个替代实现,可以澄清事情的实际工作方式。

变化:

不要注入$ compile(你不能使用它)

否转换:true(您不是使用翻译)

范围:{} - 我们创建一个空隔离范围,以便我们的模板可以工作,我们可以将指令范围与父范围隔离开来。

要求:[&#34; ngModel&#34;,&#34; ^ form&#34;] - 我们想要在元素上需要ngModel并要求元素嵌入在表单中。这些将被传递给链接函数ctrl参数。

<div
class="form-group"
ng-class="{'has-error has-feedback': form[model.$name].$invalid}"> 
<input type="text" ng-model="model.$modelValue"/></div>

<form name="form" class="simple-form" novalidate>
<select-input 
    ng-model="inputmodel">
</select-input></form>

app.directive("selectInput",function(){
return {
    restrict: "E",
    templateUrl: 'js/angular-app/test.html',
    scope: {},
    replace: true,
    require: ["ngModel", "^form"],
    link: function(scope, element, attrs, ctrl) {  
        //give our directive scope access to the model and form controllers
        $scope.model = ctrl[0];
        $scope.form = ctrl[1];          
    },
}});