【问题标题】:How to send the value from a html page to js when using AngularJS directives使用AngularJS指令时如何将值从html页面发送到js
【发布时间】:2014-11-29 08:22:34
【问题描述】:

我在 AngulrJS 中创建了一个directive

下面是我的sample.html

<uservalue user="user.userlist" change-user='user()'></uservalue >

下面是我的用户价值库

app.directive('uservalue ', function() {
    return {
        scope: {
            user:'=',
            changeUser: '&',
            readonly: '@',
            valueChange: '='
            isClickable: '@'
        },
        restrict: 'AE',
        replace: true,  
        templateUrl: 'app/partials/template.html',
    });
}

从这里它重定向到template.html 下面是我的template.html

<select><option value="">Choose user</option>
<option id = "username" data-ng-repeat="c in user" value="{{c.key}}">{{c.value}} </option>
</select> 

我可以在下拉列表中显示sample.html 中的所有用户,并且在更改下拉列表中的值时,它会转到另一个js,即user()。现在我的要求是我必须将下拉选择的值发送到user() js 函数。

任何建议!!!

【问题讨论】:

    标签: html angularjs angularjs-directive


    【解决方案1】:

    首先,您可以使用&lt;select&gt;s 做更多事情。
    除了使用&lt;option ng-repeat="..."&gt;...,您可以使用ngOptions 并将您的模型绑定到任何对象(不仅仅是字符串,如“普通”&lt;select&gt;s)。
    例如:

    <select ng-model="selectedKey" ng-options="user.key as user.value for user in users"
        <!-- Optionally add a `null` option -->
        <option value="">Choose user</option>
    </select>
    

    如果您想在所选项目发生变化时触发函数,可以使用ngChange
    此外,如果您想使用 &amp; 将参数传递给绑定到隔离范围的函数,则必须调用传递以下形式的对象的函数:{argName1: argValue1, ...}
    例如:

    <!-- In the VIEW -->
    ...change-user="setUser(userKey)"...
    
    /* In the DIRECTIVE's SCOPE */
    ...
    changeUser = '&'
    
    <!-- In the DIRECTIVE's TEMPLATE -->
    <select ng-model="selectedKey" ... ng-change="changeUser({userKey:selectedKey})">
        ...
    

    另请参阅此short demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 2022-01-19
      • 2021-10-14
      • 1970-01-01
      相关资源
      最近更新 更多