简体   繁体   English

AngularJS-更改指令中的控制器模型

[英]AngularJS - change controller model in directive

There is a simple angular example http://codepen.io/snater/pen/mHsAt , what I want is on span click, controllers model changing from directive, and text field taking model's value. 有一个简单的角度示例http://codepen.io/snater/pen/mHsAt ,我想要的是跨度单击,控制器模型从指令更改,文本字段采用模型的值。 Is this possible? 这可能吗?

I think you're using the wrong syntax to refer to ngModel, combined with the fact that probably ngModel is already used by Angular in some other way; 我认为您使用了错误的语法来引用ngModel,并结合了Angular可能已经使用了ngModel的事实。 if you change the name of the property you use to store the text, ie txtVal , and refer to it without scope. 如果您更改用于存储文本的属性的名称,即txtVal ,并且在没有scope.情况下进行引用scope. in the template, you should be able to change the value of the input upon clicking on the span. 在模板中,您应该能够在单击跨度时更改输入的值。

Something like this: 像这样:

 <div ng-controller="ctrl">

<input change-model txt-val="change_me" />

<p>{{change_me}}</p>

And in the js file: 并在js文件中:

app.directive "changeModel", ($compile) ->
  priotity: 0
  restrict: "A"
  scope:
     txtVal: '='
  link: (scope, element, attrs) -> 
     //Use txtVal instead of scope.txtVal here
     tpl = "<input ng-model='txtVal' /><span data-value='Write this to model' ng-click='clickHandle()'>Must paste text on click</span></span>"
    new_el = angular.element(tpl)
    scope.clickHandle = ->
       scope.txtVal = "some text" 

With these changes, clicking on the span updates both the value of the input and the content of the <p> 通过这些更改,单击范围将同时更新输入的值和<p>的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM