使用自定义指令

时间:2015-10-23 00:10:00

标签: javascript angularjs angularjs-directive

我已经使用了以下链接中的代码,因为我希望仅在用户使用桌面时才将指令添加到某个textarea。同样的textarea也有一个ng-keydown指令,当添加此代码时,每按一个新键就会被双重触发。

知道它为什么会发生或者我该如何解决?

angularjs-conditional-directive-only-on-desktop

更新

另一个奇怪的行为是,当你删除一个单词的最后一个字符时,它会自动删除一个前一个空格(如果有的话)。

要测试它,打开控制台并检查是否在按任何键时,您将收到消息" teste1"两次

jsFiddle

此代码的相关部分:

myApp.directive('notOnMobile', function($compile) {
    // Perform detection.
    // This code will only run once for the entire application (if directive is present at least once).
    // Can be moved into the compile function if detection result needs to be passed as attribute.
    var onMobile = false;

    return {
        compile: function compile(tElement, tAttrs) {
            if (!onMobile) tElement.attr(tAttrs.notOnMobile, '');
            tElement.removeAttr('not-on-mobile');

            return function postLink(scope, element) {
                $compile(element)(scope);
            };
        }
    };
});

<textarea ng-model="main.queryString"
          rows="1"
          ng-keydown="main.textareaAction($event)"
          not-on-mobile="auto-focus"></textarea>

1 个答案:

答案 0 :(得分:3)

您需要为指令添加终端和优先级。所以它不会两次编译元素:

- (void)exportUsers {
    NSLog(@"exportUsers method reached");

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Account" inManagedObjectContext:_context]];
    NSError *error = nil;

    NSArray *objectsForExport = [_context executeFetchRequest:request error:&error];
    NSArray *exportKeys = [NSArray arrayWithObjects:@"username", @"pin", @"credit", @"email", @"lastLogin", @"rfid", @"phoneNumber", nil];

    NSMutableArray *csvObjects = [NSMutableArray arrayWithCapacity:[objectsForExport count]];
    for (NSManagedObject *object in objectsForExport) {
        NSMutableArray *anObjectArray = [NSMutableArray arrayWithCapacity:[exportKeys count]];
        for (NSString *key in exportKeys) {
            id value = [object valueForKey:key];
            if (!value) {
                value = @"";
            }
            [anObjectArray addObject:[value description]];
        }
        [csvObjects addObject:anObjectArray];
    }
    NSLog(@"The output:%@",csvObjects);

    // need to figure out how to fetch the DeviceID and append it to the file name
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];

    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    // write array to CSV file
    CHCSVWriter *csvWriter=[[CHCSVWriter alloc]initForWritingToCSVFile:[documents stringByAppendingPathComponent:[NSString stringWithFormat:@"KegCop-users-%@.csv",idfv]]];
    [csvWriter writeLineOfFields:csvObjects];

    [csvWriter closeStream];

    [self uploadCSV];
}

- (void) uploadCSV {
    NSLog(@"inside uploadCSV method");

    // begin uploading CSV file using AFNetworking
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];

    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSString *filename = [documents stringByAppendingPathComponent:[NSString stringWithFormat:@"KegCop-users-%@.csv",idfv]];

    NSLog(@"the filename is: %@",filename);

    NSURL *url = [NSURL URLWithString:@"http://kegcop.chrisrjones.com/api/"];

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

    NSData *data = [NSData dataWithContentsOfFile:filename];

    NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"csv_files" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"KegCop-users-%@.csv",idfv] fileName:[NSString stringWithFormat:@"KegCop-users-%@.csv",idfv] mimeType:@"text/csv"];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
    }];
    [httpClient enqueueHTTPRequestOperation:operation];

}

在此处查找工作代码示例https://jsfiddle.net/h1gr0dwp/

修改

您可以在Add directives from directive in AngularJS

找到有关终端和优先级的说明