AngularJs指令 - 访问属性

时间:2013-09-03 03:34:04

标签: angularjs angularjs-directive

我喜欢angularjs,但我对指令很困惑lol。

我有以下内容:

//postcode grabber
app.directive('postcodes',
    function ($rootScope, $http) {
        return function (scope, element, attrs) {
            element.bind('change', function () {
                var targetSuburb = scope.$eval(attrs.targetSuburb);
                alert(targetSuburb);
                var modal_element = angular.element('#myModal');
                var ctrl = modal_element.controller();
                var url = '/postage/postcodes/?suburb=' + element.val();
                ctrl.setModal(url);
                modal_element.modal('show');
            });
        };
    });

这是我的HTML:

<input type="text" class='form-control' ng-model="model.suburb" postcodes id='ca_suburb' target-suburb='ca_suburb' target-state='ca_state' target-postcode='ca_postcode'>

警报总是“未定义” - 我是否缺少能够正确访问属性的内容?

2 个答案:

答案 0 :(得分:1)

如果您想访问模型的值,那么

app.directive('postcodes', function ($rootScope, $http) {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, controller) {
            element.bind('change', function () {
                console.log(controller.$viewVaue)

                var modal_element = angular.element('#myModal');
                var ctrl = modal_element.controller();
                var url = '/postage/postcodes/?suburb=' + element.val();
                ctrl.setModal(url);
                modal_element.modal('show');
            });
        }
    };
});

演示:Fiddle

如果您要提醒ca_suberb,请使用

alert(attrs.targetSuburb);

演示:Fiddle

如果ca_suberb是范围属性,那么您的代码工作正常

演示:Fiddle

答案 1 :(得分:0)

如果您想获取所输入的内容,您应该通过此范围访问

alert(scope.model[attrs.targetSuburb]);

其中attrs.targetSuburb应该是字段名称,因此您应该将模型定义为model.suburb

target-suburb='suburb'